简体   繁体   English

如果我事先不知道其对象模型,该如何解析json的字符串?

[英]How do I parse a string of json if I do not know its object model before hand?

I want to work with Open Street Map (OSM). 我想使用开放式街道地图(OSM)。 OSM keeps its data formats as flexible as possible by using key value pairs. OSM通过使用键值对来保持其数据格式尽可能灵活。 I am developing an application for Android and I am going to send it a JSON string of OSM data. 我正在为Android开发一个应用程序,并将向其发送OSM数据的JSON字符串。 What should I do if I do not know what the JSON will look like in advance? 如果我不知道JSON的样子,该怎么办? What would be the best library? 最好的图书馆是什么?

Thanks for your help, Chris 克里斯,谢谢你的帮助

This may be what you are looking for 这可能是您要寻找的

http://code.google.com/p/google-gson/ http://code.google.com/p/google-gson/

Cheers 干杯

First of all, you need to know if the JSON file contains an array or an object. 首先,您需要知道JSON文件是否包含数组或对象。 If the first nonwhite space character is a [, it's an array, if it's a {, it's an object. 如果第一个非空白字符为[,则为数组,如果为{,则为对象。 Creating JSONArray when the first char is a { or vice versa will throw a Runtime Exception. 当第一个字符为{时创建JSONArray,反之亦然,否则将抛出运行时异常。

Second off all, once you have your JSONObject, you're going to want to get data from it. 其次,一旦有了JSONObject,就将要从中获取数据。 So you have to know the name of the keys to get the values, ie 因此,您必须知道键的名称才能获取值,即

myStreet = myJsonOjbect.getString("street name")

If you're not going to get data from it, what's the point of having the json file? 如果您不打算从中获取数据,那么拥有json文件又有什么意义呢? Surely you can open the JSON in a Lint to see what the structure is. 当然,您可以在Lint中打开JSON以查看其结构。

hope this helps! 希望这可以帮助!

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

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