Home > Net >  Json Serialization/Contract Resolvers - Need to serialize object so contained list of key value pair
Json Serialization/Contract Resolvers - Need to serialize object so contained list of key value pair

Time:09-02

Since I'm having a hard time explain my question, I made a fiddle. https://dotnetfiddle.net/aa18qT

I have a class that contains a list of another class with only two properties a key and a value. Alternatively I could use a dictionary. I am serializing this to json.

Currently I have

{
  "part":1,
  "quant":2,
  "comments":"something",
  "CustomFields": [
  {
    "key":"groc1",
    "value":"truffles"
  },
  {
    "key":"groc 2",
    "value":"some thing"
  }
 ]
}

And what I want is

{
   "part":1,
   "quant":2,
   "comments":"something",
   "groc 1": "truffles", 
   "groc 2":"some thing"
}

Where groc 1 and groc 2 are two of the key value pairs. The names (groc 1) are not known at compile time and could be anything in any amount. They need to be passed as parameters to another external system with those unknown fields as the name/key.

Trying to figure out how best to do this. I've been fiddling with contract resolvers and converters but not getting anywhere..maybe something with expando objects and reflection? But seems like someone must have run into this before so maybe there is an easier way all my googling hasn't found yet. Seems like it should be simple but I've been staring at it too long. I can change the structure or type of the child object, but output needs to be like above.

Any suggestions?

CodePudding user response:

you can try this

var newObj=JObject.Parse(json);
var customFields=(JArray) newObj["CustomFields"];
newObj.Properties().Where(p=> p.Name=="CustomFields").First().Remove();

foreach (JObject item in customFields)
    newObj.Add((string) item["key"],item["value"]);

json=newObj.ToString();

json

{
  "part": 1,
  "quant": 2,
  "comments": "something",
  "groc 1": "truffles",
  "groc 2": "some thing"
}

but if you need c# classes, you have to create a custom class using a Dictionary as JsonExtensionData

Item newItem=newObj.ToObject<Item>();

public class Item
{
    public int part { get; set; }
    public int quant { get; set; }
    public string comments { get; set; }

    [JsonExtensionData]
    public IDictionary<string, object> CustomFields { get; set; }
}

CodePudding user response:

Thank you Serge and Dbc, JsonExtensionData was the magic I was looking for. I was all over the docs, but not knowing the right terms (and after being blurry eyed from a long week) I didn't find it.

  • Related