反序列化JSON System.Text.Json [关闭]

问题描述 投票:-1回答:1

我正在尝试从别人已经完成的JSON中获取某些字段,我只需要从中获取一些信息,并在我的C#模型中使用它。我有一些我无法解决的问题。我正在使用.NET CORE 3.0 System.Text.Json。

例如,这是我的JSON:

ler: {
        "data_type": "vek",
        "ler_data_meta": {
          "ID": "0001",
        },
        "affects": {
          "typelore": {
            "typelore_data": [
              {
                "typelore_name": "ar",
                "product": {
                  "product_data": [
                    {
                      "product_name": "ever",
                      "version": {
                        "version_data": [
                          {
                            "version_value": "3.1",
                            "version_affected": "="
                          }
                        ]
                      }
                    }
                  ]
                }
              }
            }

[第一个问题:是否可以直接在ler_data_meta对象中获取值“ ID”?此刻我以这种方式得到它:

public static Vul LERManagement(string js)
        {
            Vul newVUL = new Vul();

            var jsonDoc = JsonDocument.Parse(js);
            var jsonParsed = jsonDoc.RootElement;
            var tempLER = jsonParsed.GetProperty("ler");
            //LER_ID
            newVUL.ler_id = tempLER.GetProperty("ler_data_meta").GetProperty("ID").ToString();
        }

但是也许有一种最简单的方法。

第二个问题,我无法处理JSON中的数组。如何在version_data对象中使用例如version_value?

先谢谢大家!

编辑:例如,这是我的最终模型:

    public class Vulnerability
{
    [Key]
    public string ler_id { get; set; }
    public string title { get; set; }
    public string description { get; set; }
    public string version_value { get; set; }
 }
c# json visual-studio rest asp.net-core
1个回答
1
投票

读取ID的最简单方法是使用JObject

using (StreamReader r = new StreamReader(filepath))
{
     string jsonstring = r.ReadToEnd();
     JObject obj = JObject.Parse(jsonstring);
     var idvalue = obj["ler_data_meta"]["ID"].ToString();
     Console.WriteLine(idvalue);
}

另一种方法是使用dynamic

dynamic json = JValue.Parse(jsonstring);
Console.WriteLine(json.ler_data_meta.ID);
© www.soinside.com 2019 - 2024. All rights reserved.