本文介绍了JSON.NET:序列化JSON字符串属性成JSON对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以告诉我JSON.NET有JSON数据的字符串?例如。我有这样一个类:

Is it possible to tell JSON.NET I have a string with JSON data? E.g. I have a class like this:

public class Foo
{
    public int Id;
    public string RawData;
}



我用这样的:

which I use like this:

var foo = new Foo();
foo.Id = 5;
foo.RawData = @"{""bar"":42}";



我要被序列化这样的:

which I want to be serialized like this:

{"Id":5,"RawData":{"bar":42}}

基本上我有一块已经存储作为JSON非结构化可变长度的数据,我需要完全序列化对象包含此数据的一部分。

Basically I have a piece of unstructured variable-length data stored as JSON already, I need fully serialized object to contain this data as a part.

感谢

编辑:只是为了确保它是正确的理解,这是单向的序列化,即我并不需要它反序列化回同一个对象;其它系统应处理此输出。我需要RAWDATA的内容是JSON的一部分,而不是一个单纯的字符串。

Just to make sure it is understood properly, this is one-way serialization, i.e. I don't need it to deserialize back into same object; the other system shall process this output. I need content of RawData to be a part of JSON, not a mere string.

推荐答案

您需要一个转换器来做到这一点,这里有一个例子:

You need a converter to do that, here is an example:

public class RawJsonConverter : JsonConverter
{
   public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
   {
       writer.WriteRawValue(value.ToString());
   }

   public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
   {
       throw new NotImplementedException();
   }

   public override bool CanConvert(Type objectType)
   {
       return typeof(string).IsAssignableFrom(objectType);
   }

   public override bool CanRead
   {
       get { return false; }
   }
}



然后用它装饰类:

Then decorate your class with it:

public class Foo
{
    public int Id;
    [JsonConverter(typeof(RawJsonConverter))]
    public string RawData;
}



然后,当你使用:

Then, when you use:

var json = JsonConvert.SerializeObject(foo,
                                    new JsonSerializerSettings());
Console.WriteLine (json);

这是你的输出:

{"Id":5,"RawData":{"bar":42}}

希望它能帮助

编辑:我已经更新了我的一个更有效的解决答案,前面的人逼你来序列化到再反序列化,这并不

I have updated my answer for a more efficient solution, the previous one forced you to serialize to then deserialize, this doesn't.

这篇关于JSON.NET:序列化JSON字符串属性成JSON对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-07 04:25
查看更多