2011-09-08 27 views
0

解析數組的數組我有數組的數組JSON這樣的Java:從JSON

{ 
    "width" : 500, 
    "numbers" : [ 
     [46, 11, "1674"], 
     [46, 11, "1673"], 
     [46, 11, "1677"], 
     [46, 11, "1678"], 
     [46, 11, "1674"], 
     [46, 11, 1673] 
    ] 
} 

而且我不知道如何解析它。

JSONObject json = new JSONObject(jsonString); 
JSONArray jsonArray = json.getJSONArray("numbers"); 

此代碼將引發類型錯誤匹配錯誤。

+0

什麼JSON庫您使用?它可能無法應付內部數組中的混合類型。 – michid

回答

1

嘗試GSON,下面應該做的伎倆:

import java.io.File; 
import java.io.IOException; 
import org.apache.commons.io.FileUtils; 
import com.google.gson.Gson; 

public class ReadTest { 

public static void main(String[] args) throws IOException { 
    String json = FileUtils.readFileToString(new File("json.txt")); 

    Gson gson = new Gson(); 

    A a = gson.fromJson(json, A.class); 

    System.out.println(a.width); 
    System.out.println(a.numbers[0][0]); 
    } 
} 


public class A { 
    public int width; 
    public int numbers[][]; 
} 
+0

這工作得很好!謝謝! – Thommy