簡體   English   中英

Java:從JSON解析數組數組

[英]Java: parse Array of Arrays from JSON

我有這樣的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");

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

嘗試使用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[][];
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM