仅反序列化JSON文件的一个属性

A. *_*lva 6 c# json json.net visual-studio

我遇到了一个问题.我想从服务器反序列化一个复杂的JSON响应,但我只需要它的一部分.

这是一个例子:

{
 "menu": {
  "id": "file",
  "value": "File",
  "popup": {
    "menuitem": [
      {"value": "New", "onclick": "CreateNewDoc()"},
      {"value": "Open", "onclick": "OpenDoc()"},
      {"value": "Close", "onclick": "CloseDoc()"}
    ]
  }
 }
}
Run Code Online (Sandbox Code Playgroud)

我还使用Csharp2json来获取我需要的类对象,我只是根据我的需要修改了菜单类:

    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; }
}
Run Code Online (Sandbox Code Playgroud)

现在,如果我只需要弹出值和他的孩子,我该如何反序列化?

小智 11

如果你想以艰难的方式尝试它,你实际上可以利用NewtonSoft.Json的Linq命名空间并稍微修改你的代码以获得JSON中的"弹出"元素.

你的班级结构保持不变.确保使用命名空间

using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
Run Code Online (Sandbox Code Playgroud)

然后在你的代码中,一旦你有了JSON字符串,就可以使用"JObject"静态方法"Parse"来解析JSON,就像

   var parsedObject = JObject.Parse(jsonString);
Run Code Online (Sandbox Code Playgroud)

这将为您提供JObject,您可以使用它来访问所有JSON键,就像字典一样.

var popupJson = parsedObject["menu"]["popup"].ToString();
Run Code Online (Sandbox Code Playgroud)

这个popupJson现在只有弹出键的JSON.有了这个,您可以使用JsonConvert来反序列化JSON.

var popupObj = JsonConvert.DeserializeObject<Popup>(popupJson);
Run Code Online (Sandbox Code Playgroud)

这个popupObj只有menuitems列表.

希望这可以帮助!

  • 要将 JObject 转换为自定义类,您想要做的是:/sf/answers/854608471/。 (2认同)

Ham*_*lla 9

如果您不使用Newtonsoft并且正在使用System.Text.Jsonin .NET Core,则可以使用:

var post = JsonDocument.Parse(stringifiedJson);
var cat = post.RootElement.GetProperty("category").GetString();
Run Code Online (Sandbox Code Playgroud)

您可以GetString在此处看到将值转换为字符串,还有其他重载可用于将 json 值转换为Int32等。


小智 6

.NET 5+

解决方案很简单:

using System.Text.Json;

var doc = JsonDocument.Parse(response.Content);
var popupJson= doc.RootElement.GetProperty("menu").GetProperty("popup");
Run Code Online (Sandbox Code Playgroud)


Der*_*ğlu 5

如果打算仅反序列化一个属性,我通常更喜欢使用 JsonPath,因为它具有灵活性。请检查下面的代码

var jsonQueryString = "{ 'firstName': 'John',
 'lastName' : 'doe',
 'age'      : 26,}";
JObject o = JObject.Parse(jsonQueryString);
JToken token= o.SelectToken("$.age");   
Console.WriteLine(token);
Run Code Online (Sandbox Code Playgroud)

如果您的 Json 很复杂,您可以使用 JsonPath 的强大功能。您可以查看https://support.smartbear.com/readyapi/docs/testing/jsonpath-reference.html#examples以获取 JsonPath 详细文档和示例。

我还包括以下示例以获取更多使用信息:

JObject o = JObject.Parse(@"{
        'store': {
            'book': [
            {
                'category': 'history',
                'author': 'Arnold Joseph Toynbee',
                'title': 'A Study of History',
                'price': 5.50
            },
            ...
            ]
        },
        'expensive': 10
        }");
        //gets first book object
        Console.WriteLine(o.SelectToken("$..book[0]"));
        //get first book's title
        Console.WriteLine(o.SelectToken("$..book[0].title"));

        // get authors of the books where the books are cheaper then 10 $
        foreach (var token in o.SelectTokens("$..[?(@.price < 10)].author"))
            Console.WriteLine(token);
Run Code Online (Sandbox Code Playgroud)