JToken序列化为字符串json.net

本文关键字:json net 字符串 序列化 JToken | 更新日期: 2023-09-27 18:04:31

我有一个对象…

public class myEntity
    {
        public string Foo
        {
            get;
            set;
        }
        public string Bar
        {
            get;
            set;
        }
        public JToken Quux
        {
            get;
            set;
        }
}

我发送给他们的值是:"ABC", "20090101100000"{"QuuxId":1234,"QuuxName":"Sam"}分别

当我这样做的时候:

var serializedString = JsonConvert.SerializeObject(data);

serializedString值如下:

{"Foo":"ABC","Bar":"20090101100000","Quux":"  {'"QuuxId'":1234,'"QuuxName'":'"Sam'"}"}

我希望Quux的值保持为JToken,而不是像下面这样变成字符串:

{"Foo":"ABC","Bar":"20090101100000","Quux":{"QuuxId":1234,"QuuxName":"Sam"}}

JToken序列化为字符串json.net

您不能序列化string,您必须将其Parse转换为JToken

string quux_string = "{'"QuuxId'":1234,'"QuuxName'":'"Sam'"}";
var data = new myEntity()
{
    Foo = "ABC",
    Bar = "20090101100000",
    Quux = JToken.Parse(quux_string)
};

我想这个例子可以解释你做错了什么

JToken j1 = "{'"QuuxId'":1234,'"QuuxName'":'"Sam'"}"; //this is an ordinary string
JToken j2 = JToken.FromObject(new { QuuxId = 1234, QuuxName = "Sam" });
var str1 = JsonConvert.SerializeObject(j1);
var str2 = JsonConvert.SerializeObject(j2);

str1将是:"{'"QuuxId'":1234,'"QuuxName'":'"Sam'"}"

str2将为:{"QuuxId":1234,"QuuxName":"Sam"}