简体   繁体   English

C# 使用 Newtonsoft 部分解析/反序列化 JSON

[英]C# Parse/Deserialize JSON partially with Newtonsoft

I have to extract a part of json-string using .net or newtonsoft json.我必须使用 .net 或 newtonsoft json 提取一部分 json-string。

JSON: JSON:

var json = "{\"method\":\"subtract\",\"parameters\":{\"minuend\":\"SOME_CUSTOM_JSON_OBJECT_DIFFERENT_FOR_EACH_METHOD\",\"subtrahend\":23}}";

C# Class: C# 类:

class MyJson{
    public string method { get; set; }
    //public string parameters {get; set;}
    public object parameters {get; set;}
}
  1. I do not need to parse all the children of "parameters" json-object.我不需要解析“参数”json-object 的所有子项。 "parameters" could be a very big object ([{obj1}...{obj1000}], objX of 1000 fields), parse which would be not performant. “参数”可能是一个非常大的对象([{obj1}...{obj1000}],1000 个字段的 objX),解析这将是性能不佳的。 I would like ie to pass it exactly as it is on some point, so conversion "string-C#object-string" would be redundant.我希望 ie 完全按原样传递它,因此转换“string-C#object-string”将是多余的。
  2. I do not want use Regexp or string transformations (string.Substring, Split and co), because of error margin, I know that all .net and newtonsoft string transformations based.我不想使用正则表达式或字符串转换(string.Substring、Split 和 co),因为误差幅度,我知道所有基于 .net 和 newtonsoft 的字符串转换。

Question 1: if I define a property of type "object", how newtonsoft will handle this?问题 1:如果我定义一个“对象”类型的属性,newtonsoft 将如何处理? (Documentation is worse than msdn, so I'm looking for the input from you, who already tried this). (文档比 msdn 更糟糕,所以我正在寻找已经尝试过的您的输入)。

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).
}

In perfect case: "parameters" is a string and calling在完美的情况下:“参数”是一个字符串并调用

ExtractMyJson(jsonString)

gives me the json string of parameters.给我参数的json字符串。

Basically I need the newtonsoft version of基本上我需要 newtonsoft 版本

string ExtractMyJson(jsonString){
  var p1 = jsonString.Split(",");
  // .. varios string transformations
  return pParams;
}

Note: please don't reference "dynamic" keyword or ask why no string transformations, it's the very specific question.注意:请不要引用“dynamic”关键字或询问为什么没有字符串转换,这是非常具体的问题。

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);

If you let it as object is going to receive the type Newtonsoft.Json.Linq.JObject.如果让它作为对象将接收 Newtonsoft.Json.Linq.JObject 类型。

Well Objects are treated the same way your parent object is treated.对象的处理方式与父对象的处理方式相同。 It will start from the base of the graph.它将从图表的底部开始。 So if you have something like:所以如果你有类似的东西:

Person
{
 Address Address {get;set;}
}

The Json will start Deserializing Address and then add in the Person object. Json 将开始反序列化地址,然后添加到 Person 对象中。 If you want to limit thesize of the graph depth you can use a setting like :如果要限制图形深度的大小,可以使用如下设置:

JsonConvert.DeserializeObject<List<IList<IList<string>>>>(json, new JsonSerializerSettings
 {
    MaxDepth = 2
 });

For more configurations of the JsonSerializer check JsonSerializerSettings有关 JsonSerializer 的更多配置,请查看JsonSerializerSettings

If your field is an object then that object will have the KeyValuePair of every property that it holds, based on that when you cast that field you can access that type.(the behaviour is the same as assigning a type to an object in C#).如果您的字段是一个对象,那么该对象将具有它所持有的每个属性的 KeyValuePair,基于此,当您转换该字段时,您可以访问该类型。(行为与在 C# 中为对象分配类型相同) .

Update: So if you question using JsonObject or type, well JObject is and intermediary way to construct the json format in a generic format.更新:因此,如果您对使用 JsonObject 或类型有疑问,那么 JObject 是一种以通用格式构造 json 格式的中间方式。 But using the Type deserializatin means you can ignore properties you are not interested in. Mapping to a json with a type makes more sense because it creates a new object and dismisses the old JObject.但是使用类型反序列化意味着您可以忽略您不感兴趣的属性。映射到具有类型的 json 更有意义,因为它会创建一个新对象并消除旧的 JObject。

Have you tried JTOKEN ?你试过JTOKEN吗?

It is a rather simple solution to partially read basic or nested JSONs as described in this post .这是一个相当简单的解决方案如在本描述部分读取基本或嵌套JSONs

For a nested JSON对于嵌套的JSON

{ 
"key1": {
            "key11": "value11",
            "key12": "value12"
         }
"key2": "value2"
}

it would look like this它看起来像这样

JToken token = JToken.Parse(json);
var value12 = token.SelectToken("key1.key12");

to get the element of the key "key12 .获取键"key12

I think this could go nicely with your problem.我认为这可以很好地解决您的问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM