简体   繁体   中英

when i use json.net,how to deserialize String to .net Object by customized JsonConverter

example, items in expressions maybe string,number or a Object, how to deserialize it to.net Object. I do not know how to definition .net class and do not know to implement JsonConverter.


{
    "target": {
        "propertyName": "AlertObjectInfo",
        "valueType": "string"
    },
    "source": {
        "operationName": "concat",
        "expressions": [
            "aa",
            "bb",
            2,
            {
                "operationName": "concat",
                "expressions": [
                    "Name",
                    "Tom"
                ]
            },
            {
                "operationName": "Add",
                "expressions": [
                    3,
                    4
                ]
            }
        ]
    }
}

Convert your json payload to a corresponding C# object(s). You can do this in Visual Studio using the Paste Special option under the edit menu or as noted you can use an online tool to do the conversion.

This conversion will result in something like this based on your sample payload:

public class Root
{
    [JsonPropertyName("target")]
    public Target Target { get; set; }

    [JsonPropertyName("source")]
    public Source Source { get; set; }
}

public class Source
{
    [JsonPropertyName("operationName")]
    public string OperationName { get; set; }

    [JsonPropertyName("expressions")]
    public List<object> Expressions { get; set; }
}

public class Target
{
    [JsonPropertyName("propertyName")]
    public string PropertyName { get; set; }

    [JsonPropertyName("valueType")]
    public string ValueType { get; set; }
}

Then to deserialize the json into c# objects you'll make a call like the following.

System.Text.Json

JsonSerializer.Deserialize<Root>(json);

NewtonSoft

JsonConvert.DeserializeObject<Root>(json);

If you're using Newtonsoft you'll want to replace the [JsonPropertyName("target")] attributes with [JsonProperty("target")]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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