简体   繁体   中英

How to rename and remap fields with illegal json field names

I have used json2csharp to produce some nice c# class into which I can deserialize json.

It is actually working as expected EXCEPT that json2csharp named some of the fields invalid_name . I renamed those to valid csharp names but when serialized those class are null.

I found this other SO post ... where one of the answerers said the following...

Keep in mind the class I have pasted below will not work directly, because of the naming of some of the fields in the json. You may have to rename them manually and map them.

This exactly describes my problem. Unfortunately, the answer gives no clues on actually HOW to "map them." So can someone tell me how to manually map some json arrays to c# classes.

I am using RestSharp deserializers, btw.

Any ideas?

If you are using JSON.NET as the basis or JSON parsing, you can rename your properties and then decorate them with attributes to align them back to the original JSON object.

An example is a property in JSON called 1 which is invalid in C#. This can be corrected using the following:

 [JsonProperty("1")]
 public int? One { get; set; }

There is also a JsonObject attribute if you want to edit at the class level, and also a JsonIgnore object to ignore serialisation of properties.

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