开发者

Deserializing JSON in Windows Phone 7 with Json.NET

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


{ 
    "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);


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. :-)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜