Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
967 views
in Technique[技术] by (71.8m points)

C# JSON - Serialization of multiple objects of different types, that have the same properties

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.

question from:https://stackoverflow.com/questions/65832400/c-sharp-json-serialization-of-multiple-objects-of-different-types-that-have-t

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...