C# 反序列化 JsonArray

huangapple go评论50阅读模式
英文:

C# deserialize JsonArray

问题

I have problem with serializing JSON to object with JsonArray field. Here's code I've used:

使用JsonArray字段将JSON序列化为对象时出现问题。以下是我使用的代码:

using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using System.Text.Json.Nodes;

var input = "{ \"data\": [{ \"test\": \"123\" }] }";

var deserialized = JsonConvert.DeserializeObject<Input>(input, new JsonSerializerSettings
{
    ContractResolver = new DefaultContractResolver
    {
        NamingStrategy = new CamelCaseNamingStrategy()
    }
});

public class Input
{
    public JsonArray Data { get; set; }
}

And this is error I'm getting:

我得到的错误是:

Newtonsoft.Json.JsonSerializationException: "无法找到用于类型 System.Text.Json.Nodes.JsonArray 的构造函数。路径 'data',第 1 行,位置 11。"

英文:

I have problem with serializing JSON to object with JsonArray field. Here's code I've used:

using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using System.Text.Json.Nodes;

var input = &quot;{ \&quot;data\&quot;: [{ \&quot;test\&quot;: \&quot;123\&quot; }] }&quot;;

var deserialized = JsonConvert.DeserializeObject&lt;Input&gt;(input, new JsonSerializerSettings
{
    ContractResolver = new DefaultContractResolver
    {
        NamingStrategy = new CamelCaseNamingStrategy()
    }
});

public class Input
{
    public JsonArray Data { get; set; }
}

And this is error I'm getting:

> Newtonsoft.Json.JsonSerializationException: „Unable to find a
> constructor to use for type System.Text.Json.Nodes.JsonArray. Path
> 'data', line 1, position 11.”

答案1

得分: 1

Newtonsoft Json序列化程序不知道如何处理System.Text.Json命名空间中的JsonArray。
要么将数据属性声明为JArray,要么使用System.Text.Json.JsonSerializer。

通常,只使用一个库来处理Json(要么是Newtonsoft.Json,要么是System.Text.Json),不要混合使用它们。

英文:

Newtonsoft Json serializer does not know how to handle JsonArray from System.Text.Json namespace.
Either declare data property as JArray, or use System.Text.Json.JsonSerializer.

Generally, use only one library to handle Json (either Newtonsoft.Json or System.Text.Json), do not mix them together.

huangapple
  • 本文由 发表于 2023年5月29日 17:18:37
  • 转载请务必保留本文链接:https://go.coder-hub.com/76356091.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定