从JSON到2D数组

时间:2015-07-21 10:11:11

标签: java json

我有json,我想将它们存储在2D数组中。

这是我的json

[  
   {  
      "IsStudent":true,
      "Name":"Ali",
      "age":16,
      "ID":1
   },
   {  
      "IsStudent":false,
      "Name":"Emad",
      "age":17,
      "ID":2
   }
]

所以我想将所有信息存储到2D数组中:

array [0] [0] = true

array [0] [1] = Ali

array [0] [2] = 16

array [0] [3] = 1

依旧......

我尝试过使用split和join来获取这些值,但它对我不起作用

JSONArray jarr2 = new JSONArray("my json is here");
String[] resultingArray = jarr.join("\":").split(",\"");
System.out.println(resultingArray[3]);

2 个答案:

答案 0 :(得分:0)

您可以使用库org.json并执行以下操作:

String jsonData = "[{\"IsStudent\":true,\"Name\":\"Ali\",\"age\":16,\"ID\":1},{\"IsStudent\":false,\"Name\":\"Emad\",\"age\":17,\"ID\":2}]";

JSONArray jsonArray = new JSONArray(jsonData);

for(int i = 0; i < jsonArray.length; i++)
{
    JSONObject jsonObject = jsonArray.getJSONObject(i);

    boolean isStudent = jsonObject.getBoolean("isStudent");
    String name = jsonObject.getString("Name");
    int age = jsonObject.getInt("age");
    int id = jsonObject.getInt("ID");

    //You can do the other stuf that you want with the fetched data.
}

答案 1 :(得分:0)

阅读json文件示例

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.Map;

import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;


public class Test {

    public static void main(String[] args) {
        FileReader reader;
        try {
            reader = new FileReader("/test.json");
            JsonParser jsonParser =  new JsonParser();
            JsonArray array = (JsonArray) jsonParser.parse(reader);
            searchJsonElemnet(array);
        } catch (FileNotFoundException e1) {
            e1.printStackTrace();
        }
    }

    private static void searchJsonElemnet(JsonArray jsonArray){
        String[][] matrix = new String[2][4];
        int i =0;
        int j = 0;
        for (JsonElement jsonElement : jsonArray) {
             for (Map.Entry<String, JsonElement> entry : jsonElement.getAsJsonObject().entrySet()) {
                 matrix[i][j] = entry.getValue().toString();
                 j++;
            }
            i++;
            j = 0;
        }
        for (String[] row : matrix)
        {
            for (String value : row)
            {
                System.out.println(value);
            }
        }
    }

}

输出

真 &#34;阿里&#34; 16 1 假 &#34;伊马德&#34; 17 2