Home > OS >  Deserialize json to a customize object with json.net
Deserialize json to a customize object with json.net

Time:11-15

I'm trying to deserialize json-formatted response below.

{
  "context": "xxxxxx"
  "value": [
      {
        "Id": "123"
        "Time": "2022-12-01"
      }
      {
        "Id": "123"
        "Time": "2022-12-01"
      }
      ....
  ]
}

According to this: https://www.newtonsoft.com/json/help/html/deserializeobject.htm, this code should work.

 public class WorkingSetContent
    {
        /// <summary>Collection ID</summary>
        [JsonProperty("context")]
        public string Context { get; set; }

        /// <summary>UserRelationship</summary>
        [JsonProperty("value")]
        public IList<ItemClass> Items { get; set; }
   }

But I'm getting a build error : "Change 'Items' to be read-only by removing the property setter."

I changed the setter to private to avoid this build error, then I was able to run it, but it causes a runtime error as null value is passed.

CodePudding user response:

This is the code analysis rule you're running up against.

One option is to initialize your collection property with an empty list:

    [JsonProperty("value")]
    public IList<ItemClass> Items { get; } = new List<ItemClass>();

However, the code analysis rule explicitly says:

You can suppress the warning if the property is part of a Data Transfer Object (DTO) class.

Since you're deserializing this class from JSON, I think it's safe to assume it's a DTO. I would recommend using a pattern in your .globalconfig or .editorconfig files to suppress this rule for all of your DTO model classes.

CodePudding user response:

You have to fix your json

 {
  "context": "xxxxxx",
  "value": [
      {
        "Id": "123",
        "Time": "2022-12-01"
      },
      {
        "Id": "123",
        "Time": "2022-12-01"
      }
  ]
}
  • Related