繁体   English   中英

将动态 json 对象反序列化为类

[英]deserialize a dynamic json object to a class

我正在使用外部 API 来获取一些产品信息,端点以静态结构返回一些数据,并根据我查询的产品以动态结构返回其他数据。

例如,如果我请求肥皂的数据,我会得到以下 JSON:

    { "id": 4623,
      "brand": "Fa",
      "category": "Cleansing/Washing/Soap – Body",
      "photos": {
        "name": "Photos",
        "value": [        "https//test.com/1jpg"
        ]
      },
      "productname": {
        "name": "Product Name",
        "value": "Fa Shower Cream Yoghurt Vanilla Honey"
      },
      "warningstatement": {
        "name": "Warning Statement",
        "value": "Avoid contact with eyes."
      },
      "consumerusageinstructions": {
        "name": "Consumer Usage Instructions",
        "value": "Apply directly on skin."
      
    }

如果我要查询奶酪,我会得到以下 JSON:

     {
      "id": 10838,
      "brand": "Domty",
      "category": "Cheese",
      
      "photos": {
        "name": "Photos",
        "value": [ "https://test.com/2.jpg"
        ]
      },
      "productname": {
        "name": "Product Name",
        "value": "Domty White Low Salt Cheese"
      },
      "description": {
        "name": "1312",
        "value": "Highest premium quality"
      },
      "netcontent": {
        "name": "Net Content",
        "value": "900 gm"
      }

他们提供的每一种产品都是如此。 我对照片数组、产品名称、品牌和 id 等静态数据进行反序列化没有问题,因为它们适用于每个产品,但其他动态属性是我关心的。 有没有办法反序列化为这样的类:

public class Info {
    property string key { get; set;} // to hold description, consumerusageinstructions or what every key
    property string name { get; set;}
    property string value { get; set;}
}

然后将类信息的集合添加到我的产品模型中?

一种方法是解析 Json 并查看实际实体:此示例使用 Json.Net:

var parsed = JObject.Parse(json);
var properties = parsed.Children().Cast<JProperty>();
foreach (var property in properties) {
    
    // an alternative here would be to just have a list of names to ignore
    if (!(property.Value is JObject jObject)) {
        // skip the simple property/value pairs
        continue;
    }

    if (property.Name == "productname") {
        // skip product name
        continue;
    }

    if (property.Value["value"] is JArray) {
        // skip photos
        continue;
    }

    // Add to ProductModel instance
    Console.WriteLine($"{property.Name} => {property.Value["name"]} = {property.Value["value"]}");

}

输出:

警告声明 => 警告声明 = 避免接触眼睛。
消费者使用说明 => 消费者使用说明 = 直接涂抹在皮肤上。

描述 => 1312 = 最高品质
净含量 => 净含量 = 900 克

暂无
暂无

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

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