【问题标题】:How to get Json Object without JsonArray name [duplicate]如何获取没有 JsonArray 名称的 Json 对象 [重复]
【发布时间】:2018-11-27 20:07:25
【问题描述】:

我正在尝试解析从以下链接检索到的 JSON 数据

http://fipeapi.appspot.com/api/1/carros/marcas.json

它没有 JsonArray 的名称。这是我到目前为止所尝试的。

private String getName(int position) {
    String name = "";
    try {
        //Getting object of given index
        JSONObject json = result.getJSONObject(position);

        //Fetching name from that object
        name = json.getString(Config.TAG_NAME);
    } catch (JSONException e) {
        e.printStackTrace();
    }
    //Returning the name
    return name;
}

这是Config

public class Config {
    //JSON URL
    public static final String DATA_URL = "http://fipeapi.appspot.com/api/1/carros/marcas.json";

    //Tags used in the JSON String
    public static final String TAG_USERNAME = "name";
    public static final String TAG_NAME = "fipe_name";
    public static final String TAG_COURSE = "key";
    public static final String TAG_ID_MARCA_CARRO = "id";

    //JSON array name
    public static final String JSON_ARRAY = "marcas";
}

如果您需要更多信息来帮助我解决此问题,请告诉我。提前致谢!

【问题讨论】:

标签: java json android-studio


【解决方案1】:

在 Android 中解析 JSON 数据的更简单方法是使用 Gson。与您的代码集成更简单、更容易。您只需在 build.gradle 文件中添加以下依赖项。

dependencies {
  implementation 'com.google.code.gson:gson:2.8.5'
}

现在在您的代码中,您需要创建以下类。

public class Car {
    public String name;
    public String fipe_name;
    public Integer order;
    public String key;
    public Long id;
}

现在只需解析您拥有的 JSON 字符串,如下所示。

Gson gson = new Gson();
Car[] carList = gson.fromJson(jsonResponse, Cars[].class);

您会发现 JSON 被解析为对象数组。希望有帮助。

【讨论】:

    猜你喜欢
    • 2017-04-06
    • 2012-04-27
    • 2021-10-20
    • 1970-01-01
    • 2016-05-15
    • 2015-09-20
    • 1970-01-01
    • 2017-12-16
    • 1970-01-01
    相关资源
    最近更新 更多