问题描述
我遇到了一个问题.我想反序列化来自服务器的复杂JSON响应,但是我只需要其中一部分.
I am faced with a problem.I want to deserialize a complex JSON response from a server, but I only need one part of it.
这里是一个例子:
{
"menu": {
"id": "file",
"value": "File",
"popup": {
"menuitem": [
{"value": "New", "onclick": "CreateNewDoc()"},
{"value": "Open", "onclick": "OpenDoc()"},
{"value": "Close", "onclick": "CloseDoc()"}
]
}
}
}
我还使用Csharp2json获取所需的类对象,我只是根据需要修改了菜单类:
I also used Csharp2json to get the class objects that I need, I just modified the menu class according to my needs :
public class Menuitem
{
public string value { get; set; }
public string onclick { get; set; }
}
public class Popup
{
public IList<Menuitem> menuitem { get; set; }
}
public class Menu
{
public Popup popup { get; set; }
}
public class RootObjectJourney
{
public Menu menu { get; set; }
}
现在,如果我只需要popup值和他的孩子,我应该如何反序列化?
Now, how do I deserialize if I only need the popup value and his children?
推荐答案
如果您想尝试一下,可以实际使用NewtonSoft.Json的Linq命名空间,并修改一下代码以仅获取"JSON"元素.
If you want to try it the hard way, you can actually utilize the Linq namespace of the NewtonSoft.Json and modify your code little bit to get only the "popup" elements from the JSON.
您的班级结构保持不变.确保使用名称空间
your class structure remains the same. Make sure you use the namespace(s)
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
然后在代码中有了JSON字符串后,就可以使用"JObject"静态方法"Parse"来解析JSON,例如
then in your code once you have the JSON string with you, you can use the "JObject" static method "Parse" to parse the JSON, like
var parsedObject = JObject.Parse(jsonString);
这将为您提供一个JObject,您可以使用它像字典一样访问所有JSON密钥.
This will give you the JObject with which you can access all your JSON Keys just like a Dictionary.
var popupJson = parsedObject["menu"]["popup"].ToString();
此popupJson现在仅具有用于弹出键的JSON.这样,您可以使用JsonConvert来反序列化JSON.
This popupJson now has the JSON only for the popup key.with this you can use the JsonConvert to de- serialize the JSON.
var popupObj = JsonConvert.DeserializeObject<Popup>(popupJson);
此popupObj仅包含菜单项列表.
this popupObj has only list of menuitems.
希望这会有所帮助!
这篇关于反序列化JSON文件的仅一个属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!