简体   繁体   English

当我使用 json.net 时,如何通过自定义 JsonConverter 将字符串反序列化为 .net Object

[英]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.例如,表达式中的项目可能是字符串、数字或 Object,如何将其反序列化到.net Object。 I do not know how to definition .net class and do not know to implement JsonConverter.我不知道如何定义 .net class 也不知道如何实现 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).将您的 json 有效负载转换为相应的 C# 对象。 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.您可以在 Visual Studio 中使用编辑菜单下的“ 选择性粘贴”选项执行此操作,或者如前所述,您可以使用在线工具进行转换。

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.然后要将 json 反序列化为 c# 对象,您将进行如下调用。

System.Text.Json 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")]如果您使用的是 Newtonsoft,您需要将[JsonPropertyName("target")]属性替换为[JsonProperty("target")]

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

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