首页 > 解决方案 > JSON Newtonsoft C# - 反序列化 JSON 文件中的特定字段

问题描述

我正在处理一个巨大的 JSON 文件,只需要在其中提取一些字段。我一直在寻找一些反序列化的方法,但不想用 JSON 中的所有字段在 C# 中创建整个类和对象,这将是很多无用的内存。

我可以使用 Webclient 获取 JSON 文件:

using (WebClient wc = new WebClient())
{
   jsonWeb = wc.DownloadString("http://link_to_get_JSON");
}

//Deserialize into a JObject
JObject obj = JObject.Parse(jsonWeb);

//Tried to access the info with
var val = obj.PropTwo;
var solution = obj.Descendants().OfType<JProperty>().Where(p => p.Name == "solverSolution").Select(x => x.Value.ToString()).ToArray();

我真的找不到在JObject中获取所需字段的方法。在 JSON 中,唯一需要的信息是下面的solverSolution:{}

{
   "content":
   [
      {
         "id":"f4d7e7f5-86ab-4155-8336-ca5f552cb3b4",
         "name":"m1",
         "description":"m1",
         "maxHeight":2000.0,
         "layers":6,
         "pallet":{},
         "product":{},
         "solverSolution":
         {
            "id":"106ef605-d95e-4c74-851b-63310fbcbc7d",
            "name":"solver",
            "maxHeight":2000.0,
            "layers":6,
            "solution":[
            {
               "X1":0,
               "Y1":0,
               "Z1":0,
               "X2":296,
               "Y2":246,
               "Z2":220
            },
            ...
            "default":false
         },
         "customSolutions":[0]
      },
     {},
     ...
   ],
   "pageable":{},
   "totalPages":1,
   "last":true,
   "totalElements":7,
   "first":true,
   "sort":{},
   "number":0,
   "numberOfElements":7,
   "size":20
}

在这里,我提前对社区表示感谢和感谢。干杯,

安德烈·卡斯特罗。

标签: c#jsonjson.net

解决方案


然后在您的对象中仅使用所需的属性,确保遵循所需模型的结构。

public partial class RootObject {
    [JsonProperty("content")]
    public Content[] Content { get; set; }
}

public partial class Content {
    [JsonProperty("solverSolution")]
    public SolverSolution SolverSolution { get; set; }
}

public partial class SolverSolution {
    [JsonProperty("id")]
    public Guid Id { get; set; }

    [JsonProperty("name")]
    public string Name { get; set; }

    [JsonProperty("maxHeight")]
    public double MaxHeight { get; set; }

    [JsonProperty("layers")]
    public long Layers { get; set; }

    [JsonProperty("solution")]
    public Solution[] Solution { get; set; }

    [JsonProperty("default")]
    public bool Default { get; set; }
}

public partial class Solution {
    [JsonProperty("X1")]
    public long X1 { get; set; }

    [JsonProperty("Y1")]
    public long Y1 { get; set; }

    [JsonProperty("Z1")]
    public long Z1 { get; set; }

    [JsonProperty("X2")]
    public long X2 { get; set; }

    [JsonProperty("Y2")]
    public long Y2 { get; set; }

    [JsonProperty("Z2")]
    public long Z2 { get; set; }
}

解析器将忽略未映射到对象模型属性的其余部分。

var root = Jsonsonvert.DeserializeObject<RootObject>(jsonWeb);
var solverSolution = root.Content[0].SolverSolution;

如何获得所有 SolverSolution

SolverSolution[] solutions = root.Content.Select(content => content.SolverSolution).ToArray();

推荐阅读