问题描述
我遇到了一个问题.我想反序列化来自服务器的复杂 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; }
}
现在,如果我只需要弹出值和他的孩子,我该如何反序列化?
Now, how do I deserialize if I only need the popup value and his children?
推荐答案
您实际上可以利用 NewtonSoft.Json 的 Linq 命名空间并稍微修改您的代码以仅获得弹出窗口".JSON 中的元素.
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".静态方法解析"解析 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 文件的一个属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!