Convert JSON with illegal characters in property name [duplicate]

给你一囗甜甜゛ 提交于 2019-12-13 22:20:02

问题


Beforehand; I'm using an old version of Newtonsoft.Json (4.0.8.0).

So I'm trying to write a .NET client for a webserver application. To convert all incoming packets from a json structure to .NET object i do use the JSON Serializer with the inbuilt function JToken.ToObject. This requires the target .net class to have the needed attributes named exactly as the incoming json data ones.

Now I came across a data packet which contains invalid property names in the scope of C# (.NET overall I think). It looks like this.

"12345" : {

 "Name1/Part2": {}
 "Name2/Part2": {}
 "Name3/Part2": {}
 "Name4/Part2": {}
 "Name5/Part2": {}

}

the equal .net code would be.

class DataPacket {
  public DummyObject 12345 {get; set;}


  public class DummyObject {
    public object Name1/Part2 {get; set}
    public object Name2/Part2 {get; set}
    public object Name3/Part2 {get; set}
    public object Name4/Part2 {get; set}
    public object Name5/Part2 {get; set}
  }
}

where as all property names are illegal ('starting with number', 'illegal characters -> /').

Any idea how I can solve this problem with the Major 4 Version of Newtonsoft?

Many thanks


回答1:


I believe you can use the jsonproperty attribute so for the first one something like:

class DataPacket{
                    [JSONProperty(PropertyName="1234")]
                    public DummyObject OneTwoThreeFour {get;set;}//or whatever you want to name.
                }

do that for each json property you need to convert that has illegal names



来源:https://stackoverflow.com/questions/36702526/convert-json-with-illegal-characters-in-property-name

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!