是否可以将JSON.NET生成的json与类型名称处理设置为常规json?将typenameHandling转换为常规json
我的应用程序不能假设任何关于它正在接收的类型,因为它将是许多1000个类中的1个。我只需要从json中删除类型信息。
比如我收到此JSON字符串在我的应用程序:
{
"$type": "MyAssembly.MyType, MyAssembly",
"$id": 1,
"MyValue": 5
}
我可以把它转换成此JSON:
{
"MyValue": 5
}
我试图加载原始JSON到JObject然后去除所有成员都以$
开头,但之后发现在使用阵列时失败,因为它们可能如下所示:
{
"MyArray": {
"$type": "System.Collections.List, System",
"$values": [
{
"$type": "MyAssembly.MyType, MyAssembly",
"MyValue": 5
}
]
}
}
JSON.NET中是否有任何内容允许进行这种转换?
这里是为了显示我的意思
class Program
{
static void Main(string[] args)
{
JsonSerializerSettings withNamehandling = new JsonSerializerSettings()
{
TypeNameHandling = TypeNameHandling.All,
ReferenceLoopHandling = ReferenceLoopHandling.Serialize,
PreserveReferencesHandling = PreserveReferencesHandling.All,
Formatting = Formatting.Indented
};
var obj = new MyObj();
//This is the json which my application will be receiving. My application does not know about MyObj or MyType.
var json = JsonConvert.SerializeObject(obj, withNamehandling);
Console.WriteLine(json);
//Deserialize the object without namehandling enabled
var deserializeObject = JsonConvert.DeserializeObject(json);
//Serialize again without namehandling enabled
var json2 = JsonConvert.SerializeObject(deserializeObject, Formatting.Indented);
//Metadata removed from root node but not children.
Console.WriteLine(json2);
Console.ReadLine();
}
}
class MyObj
{
public List<MyType> Types { get; set; } = new List<MyType>()
{
new MyType()
{
Value = 5
}
};
}
class MyType
{
public int Value { get; set; }
}
你想怎么办'PreserveReferencesHandling'令牌什么样'“$ ID”'和'“$ REF”'?第一个''$ id“'很容易删除,但第二个是有问题的,因为''$ ref”'只是一个指向JSON层次结构其他地方的指针。在您的问题的原始版本中,并没有要求移除'PreserveReferencesHandling'令牌,但您似乎在更新中添加了它,使其更加复杂。 – dbc