Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

c# - Json add a object to a null field

I would like to add a object to a null field

I have a json file "FileXXX" which has some variables and a collection "SomeList". This "SomeList" has a collection "Group" of its own, in which i whant to insert a collection like seen in the second entry of "SomeList".

{
  "Name": "some name",
  "Jear": 2021,
  "SomeList": [
    {
      "ID": "XXXXXX",
      "Something": "",
      "Something else": 0,
      "...": 0,
      "Group": null
    },
    {
      "ID": "YYYYYY",
      "Something": "",
      "Something else": 0,
      "...": 0,
      "Group": [
        {
          "Something": "",
          "Something else": 0
        }
      ]
    },
    ... x entrys
  ]
}

I am not using the NullValueHandling.Ignore because i am using the null value as a variable, if the "Group" information should be displayed.

What i did until now, is to create a complete new json file, paste the old data into it, add the group at the specific entry and overwrite the old json file.

So basicly i am looking for the code below without the null exception popping up.

if (FileXXX.Somelist[0].Group == null)
{
    FileXXX.Somelist[0].Group.Add(myGroupObject);
}

is there simple way to achieve this?


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

1 Answer

0 votes
by (71.8m points)

You are invoking Add on null object that's why you are getting null ref exception. In case of null, first you should initialize the collection and add the object in that.

if (FileXXX.Somelist[0].Group == null)
{
    FileXXX.Somelist[0].Group = new List<YourGroupObjectType>() { myGroupObject };
}

The below is other way to write to initialize and add object in collection

FileXXX.Somelist[0].Group = new List<YourGroupObjectType>();
FileXXX.Somelist[0].Group.Add(myGroupObject);

In case you are looking for other approaches then you can explore

  1. Writing own JsonConverter so that while reading during deserialization if group is null then initialize with required object
  2. Use backing field on the property so that in case if collection is null during deserialization then collection is initialized with required object.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...