【问题标题】:Java: parse Array of Arrays from JSONJava:从 JSON 解析数组
【发布时间】:2011-09-08 08:41:24
【问题描述】:

我有一个这样的 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");

此代码引发类型不匹配错误。

【问题讨论】:

  • 你使用什么 Json 库?它可能无法处理内部数组中的混合类型。

标签: java arrays json


【解决方案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[][];
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-03-09
    • 1970-01-01
    • 2020-02-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多