How to serialize a raw json field?

好久不见. 提交于 2019-11-29 13:39:15

With Json.net you can define your own JsonConverters to apply a specific serialization behavior. You may apply it for a specific type or, if you have a view model, a specific property.

In your case you want to write the Images-string as a raw-string using JsonWriter.WriteRawValue.

Ie.

public class PlainJsonStringConverter : Newtonsoft.Json.JsonConverter
{
    public override bool CanConvert(Type objectType)
    {
        return objectType == typeof(string);
    }
    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        return reader.Value;
    }
    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        writer.WriteRawValue((string)value);
    }
}

public class MyViewModel
{
    public string id { get; set; }
    [Newtonsoft.Json.JsonConverter(typeof(PlainJsonStringConverter))]
    public string images { get; set; }
    /* ...  */
}

You will need to unserialize the data. C# offers a class to handle JSON data.

http://msdn.microsoft.com/en-us/library/system.runtime.serialization.json.datacontractjsonserializer.aspx

Excerpt from http://msdn.microsoft.com/en-us/library/bb412179.aspx :

Normally, JSON serialization and deserialization is handled automatically by Windows Communication Foundation (WCF) when you use data contract types in service operations that are exposed over AJAX-enabled endpoints. However, in some cases you may need to work with JSON data directly - this is the scenario that this topic demonstrates.

//Deserialize the JSON-encoded data into a new instance of Person by using the ReadObject method of the DataContractJsonSerializer.

stream1.Position = 0;   
Person p2 = (Person)ser.ReadObject(stream1);

//Show the results.

Console.Write("Deserialized back, got name=");
Console.Write(p2.name);
Console.Write(", age=");
Console.WriteLine(p2.age);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!