C#使用Newtonsoft部分解析/反序列化JSON [英] C# Parse/Deserialize JSON partially with Newtonsoft
问题描述
我必须使用.net或newtonsoft json提取json-string的一部分.
I have to extract a part of json-string using .net or newtonsoft json.
JSON:
var json = "{\"method\":\"subtract\",\"parameters\":{\"minuend\":\"SOME_CUSTOM_JSON_OBJECT_DIFFERENT_FOR_EACH_METHOD\",\"subtrahend\":23}}";
C#类:
class MyJson{
public string method { get; set; }
//public string parameters {get; set;}
public object parameters {get; set;}
}
- 我不需要解析"parameters" json-object的所有子级.参数"可能是一个非常大的对象([{{obj1} ... {obj1000}],包含1000个字段的objX),无法进行性能分析.我希望在某点上完全按原样传递它,因此转换"string-C#object-string"将是多余的.
- 我不想使用Regexp或字符串转换(string.Substring,Split和co),因为存在错误余量,所以我知道所有.net和newtonsoft字符串转换都基于.
问题1:如果我定义对象"类型的属性,newtonsoft将如何处理?(文档比msdn差,所以我正在寻找您的意见,他们已经尝试过此操作.)
Question 1: if I define a property of type "object", how newtonsoft will handle this? (Documentation is worse than msdn, so I'm looking for the input from you, who already tried this).
static void Main(string[] args)
{
var json = "{\"method\":\"subtract\",\"parameters\":{\"minuend\":42,\"subtrahend\":23}}";
var data = JsonConvert.DeserializeObject<MyJson>(j);
// what internal representaion of data.parameters?
// How is it actually converted from json-string to an C# object (JObject/JsonObject).
}
在理想情况下:"parameters"是一个字符串,并调用
In perfect case: "parameters" is a string and calling
ExtractMyJson(jsonString)
为我提供了参数的json字符串.
gives me the json string of parameters.
基本上我需要的是newtonsoft版本的
Basically I need the newtonsoft version of
string ExtractMyJson(jsonString){
var p1 = jsonString.Split(",");
// .. varios string transformations
return pParams;
}
注意:请不要引用"dynamic"关键字或询问为什么不进行字符串转换,这是非常具体的问题.
Note: please don't reference "dynamic" keyword or ask why no string transformations, it's the very specific question.
推荐答案
如果您知道自己的参数是唯一的,则可以执行以下操作:
If you know that your parameters are unique you can do something like this:
class MyJson
{
public string method { get; set; }
public Dictionary<string,object> parameters { get; set; }
}
................
string json = "{\"method\":\"subtract\",\"parameters\":{\"minuend\":{\"img\": 3, \"real\": 4},\"subtrahend\":23}}";
var data = JsonConvert.DeserializeObject<MyJson>(json);
如果让它作为对象,将接收类型Newtonsoft.Json.Linq.JObject.
If you let it as object is going to receive the type Newtonsoft.Json.Linq.JObject.
这篇关于C#使用Newtonsoft部分解析/反序列化JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!