未知的JSON对象/数组中的内容是什么?

时间:2015-07-28 15:30:11

标签: android json facebook-graph-api

我想得到一个朋友列表' Android中的Facebook API中的名称。在这个过程中,我想学习如何阅读JSON对象/数组。

我已经传递给了我的JSONObject和/或JSONArrays。我不知道他们中有什么*。一旦我知道哪些字段存在,我知道如何读取数据,但据我所知,没有密钥,我无法读取任何内容。即使有钥匙,我怎么能分辨它里面的内容?

基本上,我想要一段代码如下:

JSONArray mArray = response.getJSONArray();
String theEntireDatabase = mArray.getStringOFEntireDatabase();

并让它响应一个如下所示的字符串:

{
   "phoneNumber": [
      {
         "type": "work",
         "num": "11111"
      },
      {
         "type": "home",
         "num": "2222"
      }
   ],
   "address": {
      "state": "World",
      "address": "infinite space, 000",
      "city": "Android city"
   },
   "surname": "Swa",
   "name": "Android"
}

事先不了解数据库中的内容?

*它可能是"颜色:"它可能是"核威胁等级:"我所知道的一切。

我试过这个,但它只提供了密钥:Javascript get JSON key Name

4 个答案:

答案 0 :(得分:1)

JSONObject#keys will tell you what keys are defined for the object. JSONArray#length will tell you how many entries are in the array (and therefore the range of values you can use for index with the other methods: 0 through length() - 1). JSONObject#toString/JSONArray#toString will give you the string you've asked for.

答案 1 :(得分:1)

Take a look at Jacksons built-in tree model feature. http://wiki.fasterxml.com/JacksonTreeModel

And your code will be:

public void parse(String json)  {
       JsonFactory factory = new JsonFactory();

       ObjectMapper mapper = new ObjectMapper(factory);
       JsonNode rootNode = mapper.readTree(json);  

       Iterator<Map.Entry<String,JsonNode>> fieldsIterator = rootNode.fields();
       while (fieldsIterator.hasNext()) {

           Map.Entry<String,JsonNode> field = fieldsIterator.next();
           System.out.println("Key: " + field.getKey() + "\tValue:" + field.getValue());
       }
}

答案 2 :(得分:1)

JSONArray mArray = response.getJSONArray();
String theEntireDatabase = mArray.toString();

This should work well.
If you want the JSONArray pretty printed you can add this after the code I've just provided you.

Gson gson = new GsonBuilder().setPrettyPrinting().create();
JsonParser jp = new JsonParser();
JsonElement je = jp.parse(theEntireDatabase);
String prettyJsonString = gson.toJson(je); 

答案 3 :(得分:0)

besides the technical answers (JSONObject#toString(n) seems the easiest - see http://developer.android.com/reference/org/json/JSONObject.html),

I would often use two more pragmatic solutions:

  1. look for an API documentation... I know, it sounds crazy, but some companies do offer such a thing
  2. hack together a short javascript script to try the API and inspect the result in the developer console/firebug/whatever is handy