简体   繁体   English

使用属性名称中的 $ 反序列化 JSON

[英]Deserialize JSON with $ in property names

I have the following JSON object (the shape of the object will vary hence use of dynamic):我有以下 JSON 对象(对象的形状会有所不同,因此使用动态):

{
    "mba$maccType": [{
        "class": {
            "id": 1057,
            "intlId": "cacc"
        },
        "classA": false,
        "endDate": "4712-12-31T00:00:00",
        "histStatus": {
            "id": 5,
            "intlId": "valid"
        },
        "objClassif": {
            "id": 74,
            "intlId": "mba$macc_type"
        },
        "secUser": {
            "id": 2
        },
        "startDate": "2018-12-01T00:00:00",
        "timestamp": "2020-01-18T07:29:21"
    }
]
}

I'm using Newtonsoft.Json to parse as follows:我使用 Newtonsoft.Json 解析如下:

dynamic dyn = JObject.Parse(json);

My problem is, I'm unable to reference any dynamic properties because the parent property containing the $ gives a syntax error:我的问题是,我无法引用任何动态属性,因为包含 $ 的父属性给出了语法错误:

Console.WriteLine(dyn.mba$maccType);

How can I get to the value of "class.intlId" (ie "cacc")?如何获得“class.intlId”(即“cacc”)的值?

You can parse your JSON to JObject instead of dynamic type and access its items by key.您可以将 JSON 解析为JObject而不是dynamic类型,并通过键访问其项目。 Like get the first item from mba$maccType (since it's an array), then access a class token and intlId value from it就像从mba$maccType获取第一项(因为它是一个数组),然后intlId访问class令牌和intlId

var jObject = JObject.Parse(json);
var firstItem = jObject["mba$maccType"]?.FirstOrDefault();
var result = firstItem?["class"]?["intlId"]?.ToString(); // returns "cacc"

Supposing that the only dynamic part of your JSON structure are the property names on the outer object, you can deserialize this JSON to a Dictionary<string, List<T>> .假设 JSON 结构的唯一动态部分是外部对象上的属性名称,您可以将此 JSON 反序列化为Dictionary<string, List<T>> The benefit of doing this is that you would have clearly defined types for almost everything that's deserialized.这样做的好处是您可以为几乎所有反序列化的内容明确定义类型。

// type definitions
class ClassRecord
{
    public int id { get; set; }
    public string intlId { get; set; }
}

class Item
{
    public ClassRecord @class { get; set; }
    public bool classA { get; set; }

    // etc.
}

// deserialize
var obj = JsonConvert.DeserializeObject<Dictionary<string, List<Item>>>(json);

Console.WriteLine(obj["mba$maccType"][0].@class.id); // 1057

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

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