Parsing dynamic JSON string into string in C# using JSON.NET

自闭症网瘾萝莉.ら 提交于 2019-12-04 15:31:42

Since you have a dynamic json string, I'd recommend parsing the string as a JObject. This gives ultimate flexibility as far as processing the JSON object tree:

var parseTree = JsonConvert.DeserializeObject<JObject>("{ a: 2, b: \"a string\", c: 1.75 }");
foreach (var prop in parseTree.Properties()) {
    Console.WriteLine(prop.Name + ": " + prop.Value.ToObject<object>());
}

Another JObject example:

var parsed = JsonConvert.DeserializeObject<JObject>("{\"name\":{\"a\":2, \"b\":\"a string\", \"c\":3 } }");
foreach (var property in parsed.Properties()) {
    Console.WriteLine(property.Name);
    foreach (var innerProperty in ((JObject)property.Value).Properties()) {
        Console.WriteLine("\t{0}: {1}", innerProperty.Name, innerProperty.Value.ToObject<object>());
    }
}

If you know that you are dealing with a JSON array, you can instead parse as JArray and then look at each JObject in the array:

var properties = JsonConvert.DeserializeObject<JArray>("[{a:1}, {b:2, c:3 }]")
    .SelectMany(o => ((JObject)o).Properties())
    .ToArray();
foreach (var prop in properties) {
    Console.WriteLine(prop.Name + ": " + prop.Value.ToObject<object>());
}

For even more flexibility, you can parse as a JToken.

For that kind of dynamic JSON, you might want to consider something less cumbersome than JSON.NET, such as SimpleJson (https://github.com/facebook-csharp-sdk/simple-json). It's just a .cs file that you copy/paste in your project or that you install through NuGet.

It supports "dynamic" and is extremely easy to use.

For instance, if you have a JSON such as:

{
  "inputs" : ["a", "b", "c"],
  "outputs" : ["c", "d", "e"]
}

You can parse it:

dynamic sys = SimpleJson.DeserializeObject(jsonString);

And then access everything straightaway:

foreach(var attr in sys) {
  foreach( var name in attr ) {
      Console.WriteLine("In {0} with name: {1}", attr, name);
  }
}

You could of course also have accessed by name or index:

Console.WriteLine(sys["inputs"][0]);

which would print 'a'.

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