skip to Main Content

I want to de-serialize a JSON where a node contains values which comma-separated. But the object which contains the comma returns null when deserializing.

Input JSON:

{
  "SolutionTabletSubSectionUId": "3fa85f64-5717-4562-b3fc-2c963f66afa6",
  "SolutionTabletSubSectionId": 1,
  "SolutionTabletUId": "3fa85f64-5717-4562-b3fc-2c963f66afa6",
  "Title": "string",
  "SubTitle": "string",
  "Description": "string",
  "Link": "www.google.com,www.facebook.com",
  "LinkDisplayName": "DisplayName1,DisplayName2",
  "SolutionTabletConfigurationUId": "3fa85f64-5717-4562-b3fc-2c963f66afa6",
  "SolutionTabletTemplateUId": "3fa85f64-5717-4562-b3fc-2c963f66afa6",
  "ImageName": "string",
  "ImagePath": "string",
  "DisplayOrderId": 0,
  "TemplateComponentUId": "3fa85f64-5717-4562-b3fc-2c963f66afa6",
  "FooterTitle": "string",
  "FooterDescription": "string"
}

Code:

var list = new List<MyList>();
list.Add(JsonConvert.DeserializeObject<MyClass>(input));
MySubClass resultSet = new MySubClass();
resultSet.Data = list;

MyClass:

public class MyClass
{
    public Guid SolutionTabletSubSectionUId { get; set; }
    public int SolutionTabletSubSectionId { get; set; }
    public string LinkDisplayName { get; set; }
    public string Link { get; set; }
    public List<LinkNamesNode> LinkNames { get; set; }
}

public class LinkNamesNode
{
    public string LinkDisplayName { get; set; }
    public string Link { get; set; }
}

While debugging, I can see LinkNames is set to null or not hitting because the property name is not found. Please help me here to deserialize an object.

My output should look like:

{
  "LoggedInUser": "string",
  "Data": [
    {
      "SolutionTabletSubSectionUId": "3fa85f64-5717-4562-b3fc-2c963f66afa6",
      "SolutionTabletSubSectionId": 0
      "LinkNames": [
        {
          "LinkDisplayName": "DisplayName1",
          "Link": "www.google.com"
        },
        {
          "LinkDisplayName": "DisplayName2",
          "Link": "www.facebook.com"
        }
      ]
  ]
}

Please assist.

3

Answers


  1. You can work with JsonConstructorAttribute to implement the custom deserialization logic.

    Since mentioned that the size of Link and LinkDisplayName may differ in length after split by separator:

    1. Get the max value between the links and linkDisplayNames arrays.

    2. Get the value from the array by index safely with Array.ElementAtOrDefault(i) method. And add the object to the LinkNames array.

    public class MyClass
    {
        [JsonConstructor]
        public MyClass(Guid solutionTabletSubSectionUId, int solutionTabletSubSectionId, string linkDisplayName, string link)
        {
            SolutionTabletSubSectionUId = solutionTabletSubSectionUId;
            SolutionTabletSubSectionId = solutionTabletSubSectionId;
            LinkDisplayName = linkDisplayName;
            Link = link;
            LinkNames = new List<LinkNamesNode>();
            
            string[] links = new string[] {};
            if (!String.IsNullOrWhiteSpace(link))
                links = link.Split(',').ToArray();
            
            string[] linkDisplayNames = new string[] {};
            if (!String.IsNullOrWhiteSpace(linkDisplayName))
                linkDisplayNames = linkDisplayName.Split(',').ToArray();
            
            for (int i = 0; i < Math.Max(links.Length, linkDisplayNames.Length); i++)
            {
                LinkNames.Add(new LinkNamesNode
                              {
                                  Link = links.ElementAtOrDefault(i),
                                  LinkDisplayName = linkDisplayNames.ElementAtOrDefault(i)
                              });
            }
        }
        
        public Guid SolutionTabletSubSectionUId { get; set; }
    
        public int SolutionTabletSubSectionId { get; set; }
    
        public string LinkDisplayName { get; set; }
    
        public string Link { get; set; }
    
        public List<LinkNamesNode> LinkNames { get; set; }
    }
    
    Login or Signup to reply.
  2. you can solve this problem with an intermediate object because the structures of two side is not the same.

    1. create a temp class:

      public class MyTempClass
      {
      public Guid SolutionTabletSubSectionUId { get; set; }
      public int SolutionTabletSubSectionId { get; set; }

          public string Link;
      
          public string LinkDisplayName;
      
          public  MyClass ConverToMyClass()
          {
              MyClass c = new MyClass();
              c.LinkNames = new List<LinkNamesNode>();
              c.SolutionTabletSubSectionId = this.SolutionTabletSubSectionId;
              c.SolutionTabletSubSectionUId = this.SolutionTabletSubSectionUId;
              List<string> links = this.Link.Split(",").ToList();
              List<string> linkNames = this.LinkDisplayName.Split(",").ToList();
              for (int i = 0; i < links.Count; i++)
              {
                  c.LinkNames.Add(new LinkNamesNode()
                  { Link = links[i], LinkDisplayName = linkNames[i] });
              }
      
              return c;
          }
      }
      
    2. Change your code to this:

    string input = File.ReadAllText("C:working_dirstackoverflowsjsonserializeConsoleApp1ConsoleApp1jsconfig1.json");
    MyTempClass result= JsonConvert.DeserializeObject(input);
    MyClass myClass = result.ConverToMyClass();

    Hope this helps.

    Login or Signup to reply.
  3. you can create a json converter

    var result = JsonConvert.DeserializeObject<MyClass>(json, new StringConverter());
    
    public class StringConverter : JsonConverter
    {
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            var jObj = JObject.Load(reader);
            var l = ((string)jObj["Link"]).Split(",");
    
            var result = jObj.ToObject<MyClass>();
            result.LinkNames = ((string)jObj["LinkDisplayName"]).Split(",")
                                .Zip(l, (k, v) => new LinkNamesNode { LinkDisplayName = k, Link = v })
                                .ToList();
            return result;
        }
    
        public override bool CanConvert(Type objectType)
        {
            return objectType == typeof(MyClass);
        }
    
        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            throw new NotImplementedException();
        }
    }
    

    and remove these properties from your class, you don’ t need them

        public string LinkDisplayName { get; set; }
        public string Link { get; set; }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search