Martin
Martin

Reputation: 183

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

I'm trying to serialize a flat object containing only string properties into JSON. What I get is:

{
    "Inputs": {
        "prop1": "value1",
        "prop2": "value2"
    }
}

What I need is:

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

My first idea was to write a custom converter that would first cast the object to a dictionary (based on https://stackoverflow.com/a/4944547/9806449) and then iterate on the keys to build it into the desired format but it feels like there must be a simpler solution that eludes me.

Any ideas? Thanks!

Upvotes: 1

Views: 1221

Answers (1)

arslanaybars
arslanaybars

Reputation: 1853

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

Upvotes: 2

Related Questions