1. 程式人生 > >net.sf.json.JSON把JSON純數組形式轉為List

net.sf.json.JSON把JSON純數組形式轉為List

strong jar 數據 小結 user post ron sta top

net.sf.json處理一個純JSON數組要轉化為一個List類型

例如:{"userIds":[1000000,1000001]},將其轉化為一個Integer的數組

 1 package com.json.test;
 2 
 3 import java.util.List;
 4 
 5 import net.sf.json.JSONArray;
 6 import net.sf.json.JSONException;
 7 import net.sf.json.JSONObject;
 8 
 9 public class JSONTest {
10 
11     public static void main(String[] args) {
12 String json = "{\"userIds\":[1000000,1000001]}"; 13 try { 14 JSONObject json_test = JSONObject.fromObject(json); 15 Object userIds = json_test.get("userIds"); 16 JSONArray jArray = JSONArray.fromObject(userIds); 17 List data = jArray.toList(jArray);//該方法已過時
18 for (Object object : data) { 19 System.out.println(object); 20 } 21 // 創建JSON解析對象(兩條規則的體現:中括號用JSONArray,註意傳入數據對象) 22 // 取得數組長度 23 int length = jArray.size(); 24 // 回想數組的取值的方式? --->for循環遍歷數組--->得到值 25 for
(int i = 0; i < length; i++) { 26 // 根據解析的數據類型使用該類型的get方法得到該值,打印輸出 27 String string = jArray.getString(i); 28 System.out.println(string); 29 } 30 } catch (JSONException e) { 31 } 32 } 33 34 }

參考:java中string與json互相轉化:http://blog.csdn.net/miaozhenzhong/article/details/52585726

小結:

  如果在開發中接受前端傳入的JSON對象,建議以對象傳入,處理完結果也以對象傳出,萬物皆對象嘛!

  private List<Integer> userIds;直接以一個對象接受更方便。

net.sf.json.JSON把JSON純數組形式轉為List