0

Here is a data contract

class A
{
    public string Name{get;set;}
}

We are going to use var obj = JsonConvert.DeserializeObject<A>(jsongString) to deserialize the json string into an object. But the json looks like:

{
    "#Name#": "A"
}

Any change or inheritage are not allowed to class A in A.cs file, such as add attribute [JSONProperty(PropertyName="#Name#")] to property. Is it possible to deserialize the string with a customed deserialize settings, what I want is just like:

var deserializeSetting = new CustomedSettings();
var obj = JsonConvert.DeserializeObject<A>(jsonString, deserializeSetting);
Fewfy
  • 135
  • 1
  • 1
  • 6
  • Is this a Json.net specific question? Or are you looking for any specific solution in .NET? – Bernard Vander Beken May 13 '19 at 08:38
  • 1
    If it's Json.net specific here is your dupe : [How can I parse a JSON string that would cause illegal C# identifiers?](https://stackoverflow.com/questions/24536533/how-can-i-parse-a-json-string-that-would-cause-illegal-c-sharp-identifiers) , [Convert JSON with illegal characters in property name](https://stackoverflow.com/questions/36702526/convert-json-with-illegal-characters-in-property-name). And documentation [newtonsoft JsonPropertyAttribute name](https://www.newtonsoft.com/json/help/html/JsonPropertyName.htm) – xdtTransform May 13 '19 at 08:41
  • Thanks for your help, but the answers seems that it need to add JsonProperty attribute to the data contract class, which is not allowed to me. – Fewfy May 13 '19 at 08:49
  • Our comments were not clear enought. Let me reformulate: **Are you using "Json.net", "Newtonsoft Json.net"? - Yes or No?**. If you have any requirement that will invalidate any answer please add them to your question using [edit] button. And please be precise on the "Im not allowed" part. – xdtTransform May 13 '19 at 08:54
  • 2
    The requirement is not enought to invalidate the dupe answer. The solution remain the same just create a class A_bis and add a projection from A_bis to A. It's ok to have a special class to map a Json, then a buissness calss that is the object you will work with. Is that ok? The solution using a dictionarry is also valid, adding a slect to project to the real class. – xdtTransform May 13 '19 at 08:58
  • Thanks, question description updated – Fewfy May 13 '19 at 09:12
  • Since you said you cannot modify the class, you'll need to use a ContractResolver to map the properties programmatically. You can use the [`DynamicMappingResolver`](https://stackoverflow.com/a/38112291/10263) from [Json.NET deserialize or serialize json string and map properties to different property names defined at runtime](https://stackoverflow.com/q/38111298/10263) to do this. A working demo for your example class and JSON is [here](https://dotnetfiddle.net/lZ5ikA). – Brian Rogers May 13 '19 at 16:25

0 Answers0