Parsing JSON using Json.net

后端 未结 5 967
既然无缘
既然无缘 2020-11-22 07:19

I\'m trying to parse some JSON using the JSon.Net library. The documentation seems a little sparse and I\'m confused as to how to accomplish what I need. Here is the forma

5条回答
  •  不要未来只要你来
    2020-11-22 08:02

    (This question came up high on a search engine result, but I ended up using a different approach. Adding an answer to this old question in case other people with similar questions read this)

    You can solve this with Json.Net and make an extension method to handle the items you want to loop:

    public static Tuple ToTuple(this JToken token)
    {
        var type = token["attributes"]["OBJECT_TYPE"].ToString();
        var x = token["position"]["x"].Value();
        var y = token["position"]["y"].Value();
        return new Tuple(type, x, y);
    }
    

    And then access the data like this: (scenario: writing to console):

    var tuples = JObject.Parse(myJsonString)["objects"].Select(item => item.ToTuple()).ToList();
    tuples.ForEach(t => Console.WriteLine("{0}: ({1},{2})", t.Item1, t.Item2, t.Item3));
    

提交回复
热议问题