How to recursively deserialize dynamic JSON into .NET objects using Json.NET on windows phone

≯℡__Kan透↙ 提交于 2019-12-08 00:44:44

问题


I am receiving some dynamic JSON in a windows phone app and I need to be able to completely deserialize it into objects that can be saved into isolated storage.

For this application it would be best to avoid becoming locked into a class structure because I cannot predict exactly what type of JSON I will be getting back from a server.

Here is an example of how I am using Json.NET to deserialize:

JsonConvert.DeserializeObject<Dictionary<string, object>>(jsonString);

In this example the Values held in the dictionary may be Lists or Dictionaries or Strings.

The problem with this approach is that the JsonConvert.DeserializeObject(...) method seem to merely perform a shallow conversion. Nested objects are of type JArray or JObject. When I attempt to save these objects the following exception is thrown:

"Type Newtonsoft.Json.Linq.JArray with data contract name ArrayOfJTokenNewtonsoft.Json.Linq is not expected. Add any types not known statically to the list of known types - for example, by using the KnownTypeAttribute attribute or by adding them to the list of known types passed to DataContractSerializer."

Is there something obvious I am missing here?

On Android and iOS platforms this has been trivial to accomplish using 3rd party JSON library implementations.

Here is some sample JSON, but remember that I will not know for certain the exact structure of the JSON that I will be decoding in advance:

{
    "glossary": {
        "title": "example glossary",
        "GlossDiv": {
            "title": "S",
            "GlossList": {
                "GlossEntry": {
                    "ID": "SGML",
                    "SortAs": "SGML",
                    "GlossTerm": "Standard Generalized Markup Language",
                    "Acronym": "SGML",
                    "Abbrev": "ISO 8879:1986",
                    "GlossDef": {
                        "para": "A meta-markup language, used to create markup languages such as DocBook.",
                        "GlossSeeAlso": ["GML", "XML"]
                    },
                    "GlossSee": "markup"
                }
            }
        }
    }
}

来源:https://stackoverflow.com/questions/10568642/how-to-recursively-deserialize-dynamic-json-into-net-objects-using-json-net-on

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