简体   繁体   English

使用Json.NET在Windows Phone 7中反序列化JSON

[英]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? 你能帮助澄清WP7中反序列化JSON的过程吗?

I've got JSON that looks like this: 我有JSON看起来像这样:

{ 
    "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. 我正在尝试使用Json.NET,但这是我的理解几乎没有的地方。

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

For <TYPE> , how can I best define my expected deserialized object? 对于<TYPE> ,如何最好地定义我期望的反序列化对象? Status and Response as separate classes? 状态和响应作为单独的类? Or just one generic all-encapsulating ServerResponse class? 或者只是一个通用的全封装ServerResponse类?

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 这是我在C#,Silverlight,Windows Phone 7和/或.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. 你有一个状态anad响应的包装器,所以你需要以某种方式表示的包装类,如果你想采取简单的路径。 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. 换句话说,我正在确认drachenstern的答案,我也投了赞成票。 :-) :-)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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