简体   繁体   中英

.NET NewtonSoft JSON deserialize list with auto-increment index

My current situation is I have a json file

[
    {
        "first_name" : "Foo",
        "last_name" : "Bar",
        "gender" : 0
    },
    {
        "first_name" : "FooFoo",
        "last_name" : "BarBar",
        "gender" : 1
    }
]

and a Person class:

class Person
{
    public Id { get; private set; }
    public string FirstName;
    public string LastName;
    public int Gender; 
}

and I'm using the deserializer like this:

JArray.ToObject<List<Person>>();

or the equivalent:

JsonConvert.DeserializeObject<List<Person>>(jsonstr, ...)

although there is non in the json object itself, in the Person class there is a "Id" field and I need it to have increasing values according to the Person's position in the list.

The reason I can't make Id public property and set it after deserialize is because, it's an Id it should NOT be editable and I think is bad programming.

I've heard of JsonConverters. Is this achievable using them? I needed some help. Summing up I needed a way to deserialize Json arrays into objects' lists and automatically set them auto incrementing Ids.

Well then, thank you for your time.

You don't need to change anything in the deserialization process, you can simply do something in the constructor of the class:

static int NextId = 0;

public Person() 
{
     Id = NextId++;
}

And, yes, you definitely don't want your Id to be editable. A good pattern here would be

public int Id { get; private set;}

You can also put a [JsonIgnore] attribute on Id. This will mean this will not be assigned to.

[JsonIgnore]
public int Id { get; private set;}

To reset IDs

public static void ResetNextId(int startId)
{
    NextId = startId;
}

Person.ResetNextId(0);

There is also an [OnDeserialized] attribute you can apply to a procedure on the object to assign properties after the object has been deserialization.

[OnDeserialized]
public void OnDeserialized(StreamingContext context)
{
     // Do stuff
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM