Parsing Nested JSON Data Using Gson

Parsing nested JSON data using GSON

You just need to create a Java class structure that represents the data in your JSON. In order to do that, I suggest you to copy your JSON into this online JSON Viewer and you'll see the structure of your JSON much clearer...

Basically you need these classes (pseudo-code):

class Response
Data data

class Data
List<ID> id

class ID
Stuff stuff
List<List<Integer>> values
String otherStuff

Note that attribute names in your classes must match the names of your JSON fields! You may add more attributes and classes according to your actual JSON structure... Also note that you need getters and setters for all your attributes!

Finally, you just need to parse the JSON into your Java class structure with:

Gson gson = new Gson();
Response response = gson.fromJson(yourJsonString, Response.class);

And that's it! Now you can access all your data within the response object using the getters and setters...

For example, in order to access the first value 456, you'll need to do:

int value = response.getData().getId().get(0).getValues().get(0).get(1);

How to parse nested JSON using GSON

There is a little mistake in your code.So you should change ClientData clientData to ClientData data. Then you can get the data.Hope this will help you in parsing.

Parsing a nested json using gson

The issue is in these lines:

Type type = new TypeToken<Map<String, ArrayList<JsonFormatter>>>() {}.getType();
Map<String, ArrayList<Example>> nodeProperties = gson.fromJson(json.toString(), type);

The TypeToken is for Map<String, ArrayList<JsonFormatter>>, but you store the parsed JSON in a variable of type Map<String, ArrayList<Example>>. Unfortunately Gson.fromJson(..., Type) does not provide any type safety guarantees, therefore you must make sure that the provided Type matches the type of the variable you store the result in. Additionally due to Java's type erasure at runtime, you do not notice this JsonFormatter vs. Example mismatch until you iterate over the elements, causing the ClassCastException.

Based on the JSON data you provided, it looks to me like you could just use gson.fromJson(json.toString(), Example.class), but please verify whether that is actually correct for your use case.

GSON not parsing nested JSON objects properly

First of all, change:

Location LocationObject;

to:

private Location location;

And, you can deserialise JSON much easier:

Gson gson = new GsonBuilder().create();
Building building = gson.fromJson(json, Building.class);

Parsing nested JSON with GSON

This class will act as POJO (Plain Old Java Object) which is like a form and Gson is going to fill it.

public class OurClass {
public String Field1;
public int MessageId;
public Map<String, Object /* Here can be any object */> Message;
}

Now actually parsing.

Gson gson = new Gson();
OurClass ourClass = null;
ourClass = gson.fromJson(new FileReader("file.json"), OurClass.class);

Output of System.out.println(ourClass.Field1);

Value1

Output of System.out.println(ourClass.Message);

{Field1=Value, Field2=Value2, Field3=[Value3]}

It looks bad, but this is because of your ugly (sorry) json file.
You can view more examples and guide on this GitHub page.

Getting value from nested JSON Array via GSON on Android?

You can use JACKSON or GSON library for fast parsing of Json data using model class.
JACKSON and GSON are dedicated to processing (serializing/deserializing) JSON data.

Raw Parsing via GSON

JsonObject fetchedJSON = parsedJSON.getAsJsonObject();
//weather is an array so get it as array not as string
JsonArray jarray = fetchedJSON.getAsJsonArray("weather");
// OR you use loop if you want all main data
jobject = jarray.get(0).getAsJsonObject();
String main= jobject.get("main").getAsString();

Although if you want raw parsing then you can do like ::

JSONObject obj = new JSONObject(yourString);

JSONArray weather = obj.getJSONArray("weather");
for (int i = 0; i < arr.length(); i++)
{
String main= arr.getJSONObject(i).getString("main");
......
}

Get data from nested json using GSON

Your response modeled into a POJO class:

Model.kt

data class Model(
val operation: Operation,
val details: List<Detail>
)

data class Operation(
val result: Result
)

data class Result(
val message: String,
val status: String
)

data class Detail(
val id: String,
val user: String,
val technician: String,
val account: String,
val status: String
)

Class where you make the request:

val url = "https://myURL"
val request = Request.Builder().url(url).build()

val client = OkHttpClient()
client.newCall(request).enqueue(object :Callback{
override fun onFailure(call: Call, e: IOException) {
println("Failed - onFailure")
}

override fun onResponse(call: Call, response: Response) {
val body = response?.body()?.string()
println(body)

val gson = GsonBuilder().create()
gson.fromJson(body, Model::class.java)

}

})

How do I deserialize a nested JSON array using GSON?

You can not skip root JSON object. The simplest solution in this case is - create root POJO:

class Response {
@SerializedName("value")
private List<Customer> customers;

// getters, setters
}

And you can use it as below:

return gson.fromJson(json, Response.class).getCustomers();


Related Topics



Leave a reply



Submit