Biribu
Biribu

Reputation: 3823

Read integer or doubles from JsonArray in C#

I have to receive a json file from my server and I need to parse it. Until now, I receive all fields as strings:

{"key1":"12", "key2":"23.5",...}

I read it like this:

JsonArray root = JsonValue.Parse(jsonString).GetArray();

for (uint i = 0; i < root.Count; i++)
        {
            int id = Convert.ToInt32(root.GetObjectAt(i).GetNamedString("id"));
            int state = Convert.ToInt32(root.GetObjectAt(i).GetNamedString("state"));
 .....

But now, I receive some of the data as integers or doubles and I don't know how to parse it in the way I did until now because there is no method to return an int with a string given.

{"key1":12, "key2":23.5,...}

Upvotes: 0

Views: 327

Answers (1)

ErikHeemskerk
ErikHeemskerk

Reputation: 1701

System.Json does not allow you to see the difference between integers and floating point numbers. You might want to try Json.NET, which does:

var parsed = JObject.Parse("{\"key1\":12, \"key2\":23.5 }");

foreach (JProperty node in parsed.Children())
{
    Console.WriteLine("{0}: {1}", node.Name, node.Value.Type);
}

The output:

key1: Integer
key2: Float

Of course, there are other libraries out there that can deal with JSON, but at least Json.NET works with Silverlight and supports your scenario.

Upvotes: 1

Related Questions