gpt4 book ai didi

c# - 这两种 JSON 格式有什么区别?

转载 作者:太空狗 更新时间:2023-10-29 19:46:52 25 4
gpt4 key购买 nike

我有以下简单的类:

public class Test
{
public string property1 { get; set; }
public string property2 { get; set; }
}

当我尝试使用以下方法将其序列化为 JSON 时:

Test t = new Test() { property1 = "p1", property2 = "p2" };
var serializedData = JsonConvert.SerializeObject(t, Formatting.None);

我得到如下所示的 JSON:

enter image description here

当我尝试将它提交到 WEB API 应用程序时,它会显示为 null。我在内容 header 中使用 application/json

如果我改为提交相同的类作为字符串开始,它工作正常:

string test = "{\"property1\":\"p1\",\"property2\":\"p2\"}";
var serializedData = JsonConvert.SerializeObject(test, Formatting.None);

但它在 Visualizer 中看起来像这样:

enter image description here

如果我将两个字符串粘贴到记事本中,它们看起来完全一样。

知道为什么类序列化不起作用吗?

最佳答案

JSON 序列化工作正常。在第一种情况下,当您序列化对象时,它会返回普通的 JSON:

{
"property1": "p1",
"property2": "p2"
}

在第二种情况下,您已经手动序列化了 JSON,并且您正在尝试第二次序列化它,这会导致一个新的 JSON 包含一个 JSON 本身作为单个值或更可能是单个键:

{ "{\"property1\":\"p1\",\"property2\":\"p2\"}" }

您可以通过运行以下代码来测试第二个字符串是否已序列化:

var serializedData2 = JsonConvert.DeserializeObject(test);

它应该返回 JSON 的键值对:

{
"property1": "p1",
"property2": "p2"
}

我猜 null 值来自其他地方。

关于c# - 这两种 JSON 格式有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30202793/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com