Deserializing JSON in Windows Phone 7 with Json.NET

扶醉桌前 提交于 2019-12-11 10:19:35

问题


I know that there are countless questions about this. I've read many of them, but to little understanding. Can you help clarify the process of deserializing JSON in WP7?

I've got JSON that looks like this:

{ 
    "status" : {
        "code" : 99 ,
        "message" : "Already checked in" 
    },

    "response" : {
        "token" : "faisdufhdaisuflasdkf",
        "distance" : 20,
        "angle" : 45
    }   
}

I am trying to use Json.NET, but this is where my understanding is pretty much naught.

 var deserializedJSON = JsonConvert.DeserializeObject<Dictionary<string, <TYPE> >>(JsonString);

For <TYPE>, how can I best define my expected deserialized object? Status and Response as separate classes? Or just one generic all-encapsulating ServerResponse class?

Also, how do I know that this serializer will assign the correct output to the correct class member variables? if I have

class Status {
    string code;
    string message;
}

How do I know those will be assigned properly?

Thanks. Apologies if this seems trivial. This is my very first project in C#, Silverlight, Windows Phone 7, and/or .NET


回答1:


{ 
    "status" : {
        "code" : 99 ,
        "message" : "Already checked in" 
    },

    "response" : {
        "token" : "faisdufhdaisuflasdkf",
        "distance" : 20,
        "angle" : 45
    }   
}

translates to

public class item {
    public status status { get; set; }
    public response response { get; set; }
}
public class status {
    public int code { get; set; }
    public string message { get; set; }
}
public class response {
    public string token { get; set; }
    public int distance { get; set; }
    public int angle { get; set; }
}

but in this case item is anonymous (which is still valid)

and then use it like this:

var deserializedJSON = JsonConvert.DeserializeObject<item>(JsonString);



回答2:


You have a wrapper around the status anad response, so you need that wrapper class represented in some way, if you want to take the easy path. If you don't want to automagically deserialize, you can take control and avoid the wrapper, but I don't see why this would be a superior option for what you are trying to do. In other words, I am confirming drachenstern's answer, which I also voted on. :-)



来源:https://stackoverflow.com/questions/5241049/deserializing-json-in-windows-phone-7-with-json-net

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!