【问题标题】:Best way to Deserialize JSON to Dynamic using C#使用 C# 将 JSON 反序列化为动态的最佳方法
【发布时间】:2022-07-08 03:06:55
【问题描述】:

我想知道使用 NewtonSoft.Json 和 C# 反序列化为动态的最佳方法

下面的代码有效,但我不喜欢它。我想简化它,使用“命名属性”。

主要目的是获取最后一个名为“results”的对象。它是一个对象数组。

我知道我可以使用响应对象,但我需要使用动态或通用对象。

        var searchprod = wscli.BuscarImagensPorProdutoId(prodSku.ToString());
        dynamic obj = JsonConvert.DeserializeObject<dynamic>(searchprod.Result.ToString());
        dynamic obj1 = obj.results.ToString();
        dynamic obj2 = JsonConvert.DeserializeObject<dynamic>(obj1);
        dynamic results = ((JContainer)obj2).ToList();

        if (results != null)
        {
            foreach (IEnumerable<JToken> item in results)
            {
                var prodId = item.ToList()[0];//id is first position
                var id = ((JProperty)prodId).Value.ToString();

                if (!string.IsNullOrEmpty(id))
                {
                    //Delete image
                    var res = await wscli.ExcluirImagemProduto(id);

                    if (res == null || res is string)
                    {
                        throw new Exception($"Error image {id}. Details: {(res == null ? "null" : res.ToString())}");
                    }

                    if (res.status == null || res.status.ToString() != "OK")
                    {
                        throw new Exception($"Error image {id} and product {prodSku}. Details: {JsonConvert.SerializeObject(res)}");
                    }
                }
            }
        }

json:

{  
    "count": 5,  
    "next": null,  
    "previous": null,  
    "results": [    
    {      
        "id": 62217,      
        "image": "https://io.com/image1.jpg",      
        "position": 5,      
        "title": null,      
        "video": null,      
        "add_date": "2022-07-06T22:13:14.538307",      
        "change_date": "2022-07-06T22:13:14.538331",      
        "product": 12528,      
        "skus": []    
    },    
    {      
        "id": 62216,      
        "image": "https://io.com/image2.jpg",      
        "position": 4,      
        "title": null,      
        "video": null,      
        "add_date": "2022-07-06T22:13:00.435415",      
        "change_date": "2022-07-06T22:13:00.435436",      
        "product": 12528,      
        "skus": []    
    },    
    {      
        "id": 62215,      
        "image": "https://io.com/image3.jpg",      
        "position": 3,      
        "title": null,      
        "video": null,      
        "add_date": "2022-07-06T22:12:51.071782",      
        "change_date": "2022-07-06T22:12:51.071808",      
        "product": 12528,      
        "skus": []    
    },    
    {      
        "id": 62214,      
        "image": "https://io.com/image4.jpg",      
        "position": 2,      
        "title": null,      
        "video": null,      
        "add_date": "2022-07-06T22:12:35.943846",      
        "change_date": "2022-07-06T22:12:35.943871",      
        "product": 12528,      
        "skus": []    
    },    
    {      
        "id": 62213,      
        "image": "https://io.com/image5.jpg",      
        "position": 1,      
        "title": null,      
        "video": null,      
        "add_date": "2022-07-06T22:12:17.221066",      
        "change_date": "2022-07-06T22:12:17.221089",      
        "product": 12528,      
        "skus": []    
    }]
}

谢谢

【问题讨论】:

    标签: c# json object dynamic deserialization


    【解决方案1】:

    目前还不清楚你不喜欢你所拥有的东西,但如果你希望能够通过路径/属性名访问东西,这样的事情可能对你有用。 (将字符串输入 C# 让我很烦,我把它弹出到一个文件中)

    [TestMethod]
            public void GetNode()
            {
                string jsonString = File.ReadAllText("json1.json");
                Assert.IsNotNull(jsonString);
    
                JObject jObject = JObject.Parse(jsonString);
                // selects the node with results
                var resultsNode = jObject.SelectToken("$..results");
                foreach (JToken item in resultsNode)
                {
                    Console.WriteLine(item["image"]);
                }
                    
            }
    

    【讨论】:

      【解决方案2】:

      我认为阅读这篇文章会很有用。 https://inspiration.nlogic.ca/en/a-comparison-of-newtonsoft.json-and-system.text.json

      1. 如果您在现有项目中使用了 System.Text.Json 中缺少的 Newtonsoft.Json 功能,或者使用 Newtonsoft.Json 的多个属性对 DTO 进行了重度修饰,那么您在迁移过程中可能会遇到很多障碍。
      2. 如果您要开始一个新项目,我建议您使用 System.Text.Json。微软不断改进 System.Text.Json,.Net Core 3.1 和 .Net 5.0 之间有了显着的改进,微软已经开始规划 .Net 6.0。

      【讨论】:

        猜你喜欢
        • 2018-01-23
        • 2021-04-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-03-09
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多