JToken序列化为字符串json.net

时间:2015-07-23 15:21:47

标签: c# .net json.net

我有一个对象......

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

2 个答案:

答案 0 :(得分:2)

您无法序列化string,您必须Parse将其编入JToken

string quux_string = "{\"QuuxId\":1234,\"QuuxName\":\"Sam\"}";

var data = new myEntity()
{
    Foo = "ABC",
    Bar = "20090101100000",
    Quux = JToken.Parse(quux_string)
};

答案 1 :(得分:2)

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

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