Andy
Andy

Reputation: 443

Converting a Javascript JSON.stringfy string to an object using c# JSON.NET

I am developing a windows 8 app, and i have some javascript that stores a serialized object into roaming settings, i.e:

var object = [{"id":1}, {"id":2}]
roamingSettings.values["example"] = JSON.stringify(object);

I also i have a c# part to the application (for running a background task), that needs to read that JSON, and turn it into an object so i can iterate over it. And this is where i am having some issues, i am using JSON.NET to do the work, but every thing i turn turns up with an error:

// this looks like "[{\"id\":1},{\"id\":2}]"
string exampleJSON = roaming.Values["example"].ToString();
// dont know if this is correct:
List<string> example = JsonConvert.DeserializeObject<List<string>>(exampleJSON );

That give an error of:

Error reading string. Unexpected token: StartObject. Path '[0]', line 1, position 2.

So i am at a loss of what to do, i have been working on it for last few hours, and i am quite unfamiliar with c#, so resorting to the help of stackoverflow ;D

Thanks in advance for any help :)

Andy

Upvotes: 0

Views: 973

Answers (3)

I4V
I4V

Reputation: 35353

Json.Net has a nice method DeserializeAnonymousType. No need to declare a temporary class.

string json = "[{\"id\":1},{\"id\":2}]";
var anonymous = new []{new{id=0}};
anonymous = JsonConvert.DeserializeAnonymousType(json,anonymous);

foreach (var item in anonymous)
{
    Console.WriteLine(item.id);
}

You can even use the dynamic keyword

dynamic dynObj = JsonConvert.DeserializeObject(json);
foreach (var item in dynObj)
{
    Console.WriteLine(item.id);
}

Upvotes: 2

w5l
w5l

Reputation: 5746

Your json containts a collection of objects with an id property, something like this:

class IdObject {
    public int id { get; set; }
}

You could then do:

JsonConvert.DeserializeObject<List<IdObject>>(exampleJSON);

Because the IdObject class has a property id to match your json serialized value, it will be mapped back.

Upvotes: 1

Joachim VR
Joachim VR

Reputation: 2340

You are trying to parse your JSON array into a List of strings, which doesn't work. The JSON object you provide is actually a list of objects containing an integer property called 'id'.

Perhaps try creating a class (say, MyClass) with just that property, and deserialize into List.

Upvotes: 1

Related Questions