对象中的JsonConverter JsonWriter对象

时间:2015-04-30 22:25:34

标签: c# asp.net json

如何使用JsonWriter

创建类似json的json

的Json

{   
    "items" : [{"0" : {"data" : "XFDKPFSBVX", "description" : "First item"}},
               {"1" : {"data" : "UWETGIASDF", "description" : "Second item"}}]
}

转换器

class ImageBase64Converter : JsonConverter
{
    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        var list = value as List<ItemClass>;
        writer.WriteStartArray();
        foreach (var item in list)
        {
            writer.WriteStartObject();
            writer.WritePropertyName(item.Id);

            writer.WriteStartObject();
            writer.WritePropertyName("data");
            writer.WriteValue(item.Data);
            writer.WriteEndObject();

            writer.WriteStartObject();
            writer.WritePropertyName("description");
            writer.WriteValue(item.Description);
            writer.WriteEndObject();

            writer.WriteEndObject();
        }
        writer.WriteEndArray();
    }

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

    public override bool CanConvert(Type objectType)
    {
        return objectType == typeof(List<ItemClass>);
    }
}

1 个答案:

答案 0 :(得分:3)

你几乎就在那里,需要一些改进::

public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
    var list = value as List<ItemClass>;

    writer.WriteStartObject();           // << Added
    writer.WritePropertyName("items");   // << Added

    writer.WriteStartArray();
    foreach (var item in list)
    {
        writer.WriteStartObject();
        writer.WritePropertyName(item.Id);

        writer.WriteStartObject();
        writer.WritePropertyName("data");
        writer.WriteValue(item.Data);
        //writer.WriteEndObject();       // << Removed

        //writer.WriteStartObject();     // << Removed
        writer.WritePropertyName("description");
        writer.WriteValue(item.Description);
        writer.WriteEndObject();

        writer.WriteEndObject();
    }
    writer.WriteEndArray();

    writer.WriteEndObject();             // << Added
}