Serialize Dictionary as Array (Of Key Value Pairs)

Serialize dictionary as array (of key value pairs)

Ah, it turns out this is as straightforward as I'd hoped. My Dictionary<k,v> is subclassed already and I found that I can annotate it with [JsonArrayAttribute]. That gives me exactly the format I need;

"MyDict": [
{
"Key": "Apples",
"Value": {
"Taste": 1341181398,
"Title": "Granny Smith",
}
},
{
"Key:": "Oranges",
"Value:": {
"Taste": 9999999999,
"Title": "Coxes Pippin",
}
},
]

Serialize Dictionary , as array in Json.NET

I was able to get this converter to work.

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;

public class CustomDictionaryConverter : JsonConverter
{
public override bool CanConvert(Type objectType)
{
return (typeof(IDictionary).IsAssignableFrom(objectType) ||
TypeImplementsGenericInterface(objectType, typeof(IDictionary<,>)));
}

private static bool TypeImplementsGenericInterface(Type concreteType, Type interfaceType)
{
return concreteType.GetInterfaces()
.Any(i => i.IsGenericType && i.GetGenericTypeDefinition() == interfaceType);
}

public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
Type type = value.GetType();
IEnumerable keys = (IEnumerable)type.GetProperty("Keys").GetValue(value, null);
IEnumerable values = (IEnumerable)type.GetProperty("Values").GetValue(value, null);
IEnumerator valueEnumerator = values.GetEnumerator();

writer.WriteStartArray();
foreach (object key in keys)
{
valueEnumerator.MoveNext();

writer.WriteStartObject();
writer.WritePropertyName("key");
writer.WriteValue(key);
writer.WritePropertyName("value");
serializer.Serialize(writer, valueEnumerator.Current);
writer.WriteEndObject();
}
writer.WriteEndArray();
}

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

Here is an example of using the converter:

IDictionary<string, int> dict = new Dictionary<string, int>();
dict.Add("some key", 1);
dict.Add("another key", 5);

string json = JsonConvert.SerializeObject(dict, new CustomDictionaryConverter());
Console.WriteLine(json);

And here is the output of the above:

[{"key":"some key","value":1},{"key":"another key","value":5}]

Json.net serializing a flat object to key-value pair array

If I understand correctly. This is basic serializing. you wanted to serialize your object with key, value pair.

public class Obj
{
public Obj(string key, string value)
{
Key = key;
Value = value;
}

public string Key { get; set; }

public string Value { get; set; }
}

the main,

 static void Main(string[] args)
{
var response = new Dictionary<string, List<Obj>>();
var inputObjs = new List<Obj>();

inputObjs.Add(new Obj("prop1", "value1"));
inputObjs.Add(new Obj("prop2", "value2"));

response.Add("Inputs", inputObjs);

var serializedObj = JsonConvert.SerializeObject(response);

Console.ReadKey();
}

I used Newtonsoft for serializing the object

you will get this result,

{
"Inputs": [{
"key": "prop1",
"value": "value1"
},
{
"key": "prop2",
"value": "value2"
}
]
}

JSON convert dictionary to a list of key value pairs

Convert it to a list of key value pairs before passing to the JSON serializer:

JsonConvert.SerializeObject(new List<KeyValuePair<string,string>>(dictionary));


Related Topics



Leave a reply



Submit