2

I have used JSON serialization quite a bit, but have come across a scenario (That I have not encountered before) in which I have an object that can contain any number of similar objects, with the same properties. For example

{
"Objects": {
   "ObjectA": {
     "prop1": 6601,
     "prop2": "Prop",
     "propParams": [
       {
         "Type": 0,
         "Name": "name"
       }
     ]
  },
  "ObjectB ": {
    "prop1": 6601,
    "prop2": "Prop",
    "propParams": []
    }
   }
}

Unfortunately it is not a list/array of objects. Which is one of my issues.

So I have a few things that I could use some help, suggestions, guidance, etc..
on on how to deal with them.

I feel I should start with the objects in Objects first. As you can see, they are of different types, but contain the same properties, and this will hold true for any object in this Objects class. Is there a way to take an object and "Convert" it to a Standard object, so long it contains the appropriate properties? I am thinking something with JsonConvert. Maybe with the Object Type as a string property of the "Standard" object.

2nd is there a way to make the objects in Objects to an array/list regardless of its object type? I understand this may have to done first, but it made sense to ask in the order I did.

I am currently scouring the web for any other help, but figured I would ask here.

1 Answer 1

2

Objects should be treated as a Dictionary<string, Standard>.

For example, this LINQPad query:

void Main()
{
    JsonConvert.DeserializeObject<Payload>(@"{
    ""Objects"": {
       ""ObjectA"": {
         ""prop1"": 6601,
         ""prop2"": ""Prop"",
         ""propParams"": [
           {
             ""Type"": 0,
             ""Name"": ""name""
           }
         ]
      },
      ""ObjectB "": {
        ""prop1"": 6601,
        ""prop2"": ""Prop"",
        ""propParams"": []
        }
       }
    }").Dump();
}

public class Payload
{
    public Dictionary<string, Standard> Objects{get;set;}
}

public class Standard
{
    public int Prop1{get;set;}
    public string Prop2{get;set;}
    public List<Dictionary<string, object>> PropParams{get;set;}
}

Will yield this result:

enter image description here

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks I never really knew that, I will give that a try.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.