Android App data format Json parsing methods and faqs

  • 2020-05-27 07:10:58
  • OfStack

(1). Analysis of Object 1:

{"url":"http://www.cnblogs.com/qianxudetianxia"}

Analytical method:
JSONObject demoJson = new JSONObject(jsonString);
String url = demoJson.getString("url");

(2). Object bis:
{"name":"android","name":"iphone"}

Analytical method:
JSONObject demoJson = new JSONObject(jsonString);
String name = demoJson.getString("name");
String version = demoJson.getString("version");
System.out.println("name:"+name+",version:"+version);

(3). Array 1:
{"number":[1,2,3]}

Analytical method:
JSONObject demoJson = new JSONObject(jsonString);
JSONArray numberList = demoJson.getJSONArray("number");
for(int i=0; i<numberList.length(); i++){
    // Because the type in the array is int So for getInt , other getString . getLong With the use 
    System.out.println(numberList.getInt(i));
}

(4). Analysis of Array bis:
{"number":[[1],[2],[3]]}

Analytical method:

// Nested array traversal 
JSONObject demoJson = new JSONObject(jsonString);
JSONArray numberList = demoJson.getJSONArray("number");
for(int i=0; i<numberList.length(); i++){
      // Gets an array of an array 
      System.out.println(numberList.getJSONArray(i).getInt(0));
}

(5). Analysis of Object and Array:
{"mobile":[{"name":"android"},{"name":"iphone"}]}

Analytical method:
JSONObject demoJson = new JSONObject(jsonString);
JSONArray numberList = demoJson.getJSONArray("mobile");
for(int i=0; i<numberList.length(); i++){
      System.out.println(numberList.getJSONObject(i).getString("name"));
}

So, what we found is that get is followed by the type of result you want to get: getType, which is very helpful to understand.
(6). Use optType:
In the example above, getType throws an exception when a node cannot be found.
If you use optType and the node cannot be found, null or the default value is returned.

JSONObject demoJson = new JSONObject(jsonString);
String url = demoJson.getString("url");
0
(7). UTF-8's BOM header causes the problem of resolving JSON exceptions
When the json file is saved as utf-8, on the windows platform, the bom header "EF BB EF" byte is generated at the beginning of the text (you need to open it with the base 106 tool to see it).
There are two solutions:
a. Use UltraEdit to open the json file and save it as UTF-8, without BOM header. If it doesn't work, open it with notepad and save it as UTF-8.
b. Use code processing to intercept the main content of json:
String jsonString = getJsonString();
jsonString = jsonString.substring(jsonString.indexOf("{"),jsonString.lastIndexOf("}")+1);


Related articles: