反序列化Json Stream

时间:2018-08-14 13:48:26

标签: c# json stream jsonserializer

例如,我使用此消息,并使用Json POST消息推送它:

[{
    "Project":"example", 
    "Ref":"001BC50C70000A21", 
    "Latitude":43.643166, 
    "Longitude":1.454769, 
    "ParkList": [{
        "Id":"001BC50C70000A21P1", 
        "State":1, 
        "DateTime":"2018-02-15T08:07:18.987Z"
    }, {
        "Id":"001BC50C70000A21P2",
        "State":1,
        "DateTime":"2018-02-15T08:11:41.824Z"
    }]
}]

我有这段代码,当我使用字符串变量时,这些代码可以正常地反序列化Json消息:

string jsonString = "[{\"Project\":\"example\", \"Ref\":\"001BC50C70000A21\", \"Latitude\":43.643166, \"Longitude\":1.454769, \"ParkList\": [{\"Id\":\"001BC50C70000A21P1\", \"State\":1, \"DateTime\":\"2018-02-15T08:07:18.987Z\"}, {\"Id\":\"001BC50C70000A21P2\",\"State\":1,\"DateTime\":\"2018-02-15T08:11:41.824Z\"}]}]";

    List<KMessage> kMsg = JsonConvert.DeserializeObject<List<KMessage>>(jsonString);
    foreach (Parklist item in kMsg[0].Parklist)
    {
          Console.WriteLine("Id: " + item.ParkId + " State: " + item.ParkState + " DateTime: " + item.ParkDateTime);
    }

我想对自己的信息流做同样的事情:

[ServiceContract]
    public interface IKService
    {
        [DataContractFormat] 
        [OperationContract] 
        [WebInvoke(
             Method = "POST",
             BodyStyle = WebMessageBodyStyle.Bare,
             RequestFormat = WebMessageFormat.Json,
             ResponseFormat = WebMessageFormat.Json,
             UriTemplate = "/state")]
        void Service(Stream KStream); 
    }

我尝试了很多方法,但是没有用(ParkList再次为空)。例如:

using (StreamReader reader = new StreamReader(KStream))
using (JsonTextReader jsonReader = new JsonTextReader(reader))
{
    JsonSerializer ser = new JsonSerializer();
    List<KMessage> kMsg = ser.Deserialize<List<KMessage>>(jsonReader);
    foreach (Parklist item in kMsg[0].Parklist)
    {
        Console.WriteLine("Id: " + item.ParkId + " State: " + item.ParkState + " DateTime: " + item.ParkDateTime);
    }
}

有关信息,我不能使用“ DataContractJsonSerializer”,因为反序列化列表对我不起作用(deserializing Json data which contain an array in c#

非常感谢您的帮助

0 个答案:

没有答案