【问题标题】:when i use json.net,how to deserialize String to .net Object by customized JsonConverter当我使用 json.net 时,如何通过自定义的 JsonConverter 将字符串反序列化为 .net 对象
【发布时间】:2022-08-14 13:07:35
【问题描述】:

例如,表达式中的项目可以是字符串、数字或对象。如何将其反序列化为 .NET object。我不知道如何定义 .NET 类,也不知道如何实现JsonConverter

{
    \"target\": {
        \"propertyName\": \"AlertObjectInfo\",
        \"valueType\": \"string\"
    },
    \"source\": {
        \"operationName\": \"concat\",
        \"expressions\": [
            \"aa\",
            \"bb\",
            2,
            {
                \"operationName\": \"concat\",
                \"expressions\": [
                    \"Name\",
                    \"Tom\"
                ]
            },
            {
                \"operationName\": \"Add\",
                \"expressions\": [
                    3,
                    4
                ]
            }
        ]
    }
}
  • Json.NET 有一个很好的示例文档:newtonsoft.com/json/help/html/SerializingJSON.htm。您在理解文档方面有困难吗?在那种情况下,你到底在挣扎什么?
  • 基本上要反序列化 json 字符串,您需要一个对应于 json 的类(=您的数据模型)。如果您不确定课程应该是什么样子,您可以使用有用的工具,例如json2csharp.com。有了它应该像调用Product deserializedItem = JsonConvert.DeserializeObject<MyDataModel>(jsonstring); 一样简单
  • 为什么需要反序列化它?你能展示完整的代码你将如何使用它吗?

标签: c# json .net serialization json.net


【解决方案1】:

将您的 json 有效负载转换为相应的 C# 对象。您可以在 Visual Studio 中使用编辑菜单下的Paste Special 选项执行此操作,或者如前所述,您可以使用online tool 进行转换。

根据您的示例有效负载,此转换将产生类似这样的结果:

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; }
}

然后要将 json 反序列化为 c# 对象,您将进行如下调用。

System.Text.Json

JsonSerializer.Deserialize<Root>(json);

牛顿软件

JsonConvert.DeserializeObject<Root>(json);

如果您使用的是 Newtonsoft,您需要将 [JsonPropertyName("target")] 属性替换为 [JsonProperty("target")]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-11-15
    • 1970-01-01
    • 1970-01-01
    • 2016-03-28
    • 2013-07-25
    • 2017-08-20
    • 1970-01-01
    相关资源
    最近更新 更多