使用属性名称中的非法字符转换JSON [英] Convert JSON with illegal characters in property name
问题描述
事先;我正在使用旧版本的Newtonsoft.Json(4.0.8.0).
Beforehand; I'm using an old version of Newtonsoft.Json (4.0.8.0).
因此,我正在尝试为Web服务器应用程序编写.NET客户端. 要将所有传入的数据包从json结构转换为.NET对象,请使用JSON序列化器和内置函数JToken.ToObject. 这要求目标.net类具有与传入的json数据名称完全相同的所需属性.
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.
现在,我遇到了一个数据包,该数据包包含C#范围内的无效属性名称(我认为总体上是.NET). 看起来像这样.
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":{
"12345" : {
"Name1/Part2": {}
"Name2/Part2": {}
"Name3/Part2": {}
"Name4/Part2": {}
"Name5/Part2": {}
}
.net代码相同.
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 -> /').
有什么想法可以使用Newtonsoft的Major 4版本解决此问题吗?
Any idea how I can solve this problem with the Major 4 Version of Newtonsoft?
非常感谢
推荐答案
我相信您可以使用jsonproperty属性,因此对于第一个属性,例如:
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.
}
对于需要转换具有非法名称的每个json属性,请执行此操作
do that for each json property you need to convert that has illegal names
这篇关于使用属性名称中的非法字符转换JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!