繁体   English   中英

使用 C# 将 JSON 反序列化为动态的最佳方法

[英]Best way to Deserialize JSON to Dynamic using C#

我想知道使用 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)}");
                    }
                }
            }
        }

杰森:

{  
    "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# 让我很恼火,我将它弹出到一个文件中)

[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"]);
            }
                
        }

我认为阅读这篇文章会很有用。 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 进行规划。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM