0

I am trying to parse the JSON data retrieved from the following link

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

It does not have a name of the JsonArray. Here is what I have tried so far.

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;
}

And here is the Config class

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";
}

Please let me know if you need more information to help me in solving this problem. Thanks in advance!

Reaz Murshed
  • 23,691
  • 13
  • 78
  • 98
Mf1399
  • 9
  • 1
  • I think you should check this https://stackoverflow.com/questions/4308554/simplest-way-to-read-json-from-a-url-in-java Or the accepted answer in this link does exactly what you want https://stackoverflow.com/questions/13196234/simple-parse-json-from-url-on-android-and-display-in-listview – Shivam Pokhriyal Nov 27 '18 at 20:17

1 Answers1

0

The easier way to parse a JSON data in Android is using Gson. It is simple and easier to integrate with your code. You just need to add the following dependency in your build.gradle file.

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

Now in your code, you need to create the following class.

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

Now simply parse the JSON string you have like the following.

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

You will find the JSON parsed as an array of objects. Hope that helps.

Reaz Murshed
  • 23,691
  • 13
  • 78
  • 98