1

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!

Martin
  • 163
  • 1
  • 9

1 Answers1

2

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"
        }
    ]
}
arslanaybars
  • 1,813
  • 2
  • 24
  • 29
  • @Martin can you try? – arslanaybars Aug 13 '18 at 10:53
  • That's not what I get. I get `[{"Key":"prop1","Value":"value1"},{"Key":"prop2","Value":"value2"}]`. – Palle Due Aug 13 '18 at 11:13
  • Ohh i see the issue. can you try now – arslanaybars Aug 13 '18 at 11:17
  • 1
    Yes, that should work. BTW, your Obj class could be replaced KeyValuePair or KeyValuePair. – Palle Due Aug 13 '18 at 11:34
  • @arslanaybars Yes this should work, thanks :). What would you suggest for mapping an object that has 60-something properties like that (will have to do a few of them actually). Would it be better to use reflection to iterate through properties or just bite the bullet and do `inputObjs.Add(new Obj("prop1", "value1"));` for each property? – Martin Aug 13 '18 at 12:13
  • I think you should retrieve this data from some source and bind the retrieved input. – arslanaybars Aug 13 '18 at 12:45