Search code examples
c#jsonjsonfx

Read JSON string as key value


I have following json:

{   
    "serverTime": "2013-08-12 02:45:55,558",
    "data": [
        {
            "key1": 1,
            "key2": {},
            "key3": {
                "key4": [
                    ""
                ],
                "key5": "test2"
            },
            "key7": 0
        },
        {
            "key8": 1,
            "key9": {},
            "key10": {
                "key4": [
                    ""
                ],
                "key9": "test2"
            },
            "key11": 0
        }
    ] 

}

I want to get values as key value pair. Something like:

jsonObject[data][0]

should give first item of the data array.

I am using JSONFx.net. But it gives strongly typed objects. I do not want that. Is there any way to parse JSON as key value as I mentioned earlier?

Thanks


Solution

  • Try this:

    using System;
    using System.IO;
    using Newtonsoft.Json;
    
    class Program
    {
        static void Main(string[] args)
        {
            var json = File.ReadAllText("input.txt");
            var a = new { serverTime = "", data = new object[] { } };
            var c = new JsonSerializer();
            dynamic jsonObject = c.Deserialize(new StringReader(json), a.GetType());
            Console.WriteLine(jsonObject.data[0]);
        }
    }