简体   繁体   中英

Deserialize JSON response with unknown object names using c# ReadObject()

So i'm trying to deserialise a JSON response implicitly back into a object instance using the following code.

 DataContractJsonSerializer jsonSerialiser = new DataContractJsonSerializer(responseType);
 responseBase = jsonSerialiser.ReadObject(responseStream);

The response if piped out as a string looks as follows

{
"20170317112739": {
    "start": {
        "SQ": 4577,
        "TS": "2017-03-17T11:26:59",
        "FisCode": "_R1-AT1_001/1_SQ4577_2017-03-17T11:26:59_0,00_0,00_0,00_0,00_0,00_vr1zl86Y_49e862eb_rNvvLM3FKh4=_DGZt+z+A3fY8zLlt2E55R8zCD/wf7yw9q/VivAiaNtxNpaTkhlTONAsD6yc+8Vcxwnm/lBalIwEI6GswC04kqg=="
    },
    "close": {
        "SQ": 4667,
        "TS": "2017-03-17T11:27:39",
        "FisCode": "_R1-AT1_001/1_SQ4667_2017-03-17T11:27:16_0,00_0,00_0,00_0,00_0,00_r/82sV+w_49e862eb_FD/gDnivnes=_LKmvkk5OEoL7EFIebQU73VDVfPGzRGOyKNLlIW1mJkvPpqS0oVdWmqiNGR0cnpT35ArF++XzO1D/q7keTJe4cA=="
    }
},

"current": {
    "start": {
        "SQ": 4670,
        "TS": "2017-03-17T11:27:39",
        "FisCode": "_R1-AT1_0/1_SQ4670_2017-03-17T11:27:39_0,00_0,00_0,00_0,00_0,00_/agx6rsw_49e862eb_qTh1/lCawvo=_f7yNP/+WUWZCojerZ9fe/wID1gll0I37swEKsauV8h7g8gSCFZ2Ykg45JjkO7BrChCBkl0ewohuGdbP4haLbrQ=="
    },
    "2017-03": {
        "SQ": 4673,
        "TS": "2017-03-17T11:27:39",
        "FisCode": "_R1-AT1_0/1_SQ4670_2017-03-17T11:27:39_0,00_0,00_0,00_0,00_0,00_/agx6rsw_49e862eb_qTh1/lCawvo=_f7yNP/+WUWZCojerZ9fe/wID1gll0I37swEKsauV8h7g8gSCFZ2Ykg45JjkO7BrChCBkl0ewohuGdbP4haLbrQ=="
    }
},
"lic": "0SvXs"

}

Simple responses from the JSON service are no problem i can simply decorate these with [DataContract] and [DataMember].

The problem with this particular service response is that item names such as will change depending on when the call is made to during other months/years. 类的项目名称将根据在其他月份/年期间进行呼叫的时间而改变。

How do i deal with this in C#?, can someone supply an example of how my class should look?

For the life of me i cannot get this data into my object class!

You can have a dynamic dictionary as suggested in this post Deserialize JSON into C# dynamic object?

Or you can implement something like this with the help of System.Web.Helpers

using (StreamReader r = new StreamReader("sample.json"))
{
    string json = r.ReadToEnd();
    dynamic data = Json.Decode(json); 
    Console.WriteLine(data["20170317112739"].start.sq);
}

Here sample.json contains your sample JSON response.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM