Friday, June 26, 2015

Deserialize JSON Object in C#

As soon as I'm done with this the project is basically done. I mean, the important part is sending and receiving data through the Web Service using JSON. I can already receive it, but I still need to send it. In my past entry, I explained how I communicated with C# by Javascript. Now, I receive a big string which is a "stringified" JSON array. What I need to do deserialize that data so that I can correctly separate the data and then INSERT it to the database. This is the code I have right now:

    [WebMethod]
    public void SyncToServer(string D)
    {
        Console.Write(D);
        var jobs = JsonConvert.DeserializeObject<Job[]>(D);
        Console.WriteLine();
    }

The string D is the JSON I'm receiving. D has a string which is the JSON array. The class Job has the exact same fields that the JSON has, so it shouldn't be a problem. And that is the exact solution I've read in every place I've searched. But it's not working. The error I'm getting is the following:

An exception of type 'Newtonsoft.Json.JsonSerializationException' occurred in Newtonsoft.Json.dll but was not handled in user code
Additional information: Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'Job' because the type requires a JSON object (e.g. {"name":"value"}) to deserialize correctly.
I will continue to try and deserialize it.

UPDATE: I now copied the JSON array string to a variable and tried executing the same code, but no change. I suspect it has to be the way I'm doing it is incorrect. I still have to keep investigating.

UPDATE 2: I tried making the JSON in the variable a JSON object with the whole array as a parameter, but it's still not working.

UPDATE 3: Wow... The problem was the JSON. It was incorrectly formatted, it had a couple of extra brackets that didn't go there. That's why it wasn't recognizing the format. Now that I've managed to figure out where the flaw was, time to go back to the Javascript and find out where exactly is it going wrong in creating the JSON.

UPDATE 4: GOT IT! In the Javascript I changed the way I was writing the JSON in the localstorage. If the localstorage was empty, I pushed the object into an array then placed it on the localstorage. The problem was that it was inserting the whole object as an array, and I needed to insert just the object. Success!

No comments:

Post a Comment