Click here to Skip to main content
15,881,248 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have a JSON that has id and parentId twice. How do I serialize this.
Here is my json
[
    {
     "id": -2147483639,
     "parentId": 37
    },
    {
    "id": -2147483636,
    "parentId": 35
    }
]


I have my Model class where I am using the constructor to set the values. I am confused on how to set the values when I have the duplicate. In my function method I am using
JsonConvert.SerializeObject(new TagModel()));

[Serializable]
  public class TagModel
  {
       public int id { get; set; }
       public int parentId { get; set; }


      public TagModel()
      {

              id = -2147483639;
              parentId = 37;


      }



  }


What I have tried:

I have tried to pass parameters in the constructors but that did not work.
Posted
Updated 23-Mar-20 9:31am

You don't have one object with the same property twice; you have an array containing two objects, each of which has the id and parentId properties once.

Serialize a list of TagModel objects, and you should get the expected JSON output.
C#
[Serializable]
public class TagModel
{
    public int id { get; set; }
    public int parentId { get; set; }
}

...

var objectToSerialize = new List<TagModel>
{
    new TagModel { id = -2147483639, parentId = 37 },
    new TagModel { id = -2147483636, parentId = 35 },
};

string json = JsonConvert.SerializeObject(objectToSerialize);
 
Share this answer
 
v2
1. What you have is already serialized; are you sure you did not mean DeSerialize?
2. You don't have duplicate properties, you have an array of similar objects

Newtonsoft can be used for this to convert the JSON to a JArray, which can then be read into a collection of objects.

Reference:
Convert JSON to Collection[^]
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900