Now that we can see the data, we can see that payments is in fact an array (values uses []).
That means you need to call rootObj.getAsJsonArray("payments") which returns a JsonArray, and it is an Iterable<JsonElement>, which means your loop should be for(JsonElement pa : paymentsObject).
Remember, each value of the array can be any type of Json element (object, array, string, number, ...).
You know that they are JsonObject, so you can call getAsJsonObject() on them.
json = (json data)
JsonParser parser = new JsonParser();
JsonObject rootObj = parser.parse(json).getAsJsonObject();
JsonArray paymentsArray = rootObj.getAsJsonArray("payments");
for (JsonElement pa : paymentsArray) {
JsonObject paymentObj = pa.getAsJsonObject();
String quoteid = paymentObj.get("quoteid").getAsString();
String dateEntered = paymentObj.get("date_entered").getAsString();
BigDecimal amount = paymentObj.get("amount").getAsBigDecimal();
}
Answer from Andreas on Stack OverflowVideos
So you have the JsonArray object with your records, here's what you do to get your functional objects:
Type type = new TypeToken<List<DataMetrics>>() {}.getType();
List<DataMetrics> records = gson.fromJson(jsonArrayThatYouHave, type);
Then you iterate through you objects and filter the ones you need. In java 8 you can do this:
List<DataMetrics> result = records.stream().filter(record -> record.name.equals("Client::Sync")).collect(toList());
This approach is converting all objects and iterating after, if exactly this part of code is performance critical, you can still iterate through json and convert only necessary objects (but i doubt that this will be actually faster than described above).
Anyway this is more maintainable and understandable code.
UPDATE:
the same for java 7 will be:
List<DataMetrics> result = new LinkedList<>();
for(DataMetrics record : records){
if(record.name.equals("Client::Sync")){
result.add(record);
}
}
Or if you want to iterate json and parse only required ones heres what you can do:
Type type = new TypeToken<List<DataMetrics>>() {}.getType();
for(JsonElement elem : jsonArrayThatYouHave) {
if (elem.getAsJsonObject().get("name").getAsString().equals("Client::Sync")) {
result.add(gson.fromJson(elem, type));
}
}
but I dont think this is actually faster than the first one because in both cases you are converting json to java functional object with parser and getting JsonArray or anything else. Taking into consideration the fact that both are Googles libs, i assume that parsing from JsonObject to some specific type with gson is way faster than from String (raw json) to the same specific type...
You can simplify your code and retrieve the first_type array using the following code. Same code should pretty much work for the second_type array as well:
JsonArray types = map_json
.getAsJsonObject("waypoints")
.getAsJsonObject("ship")
.getAsJsonArray("first_type";
for(final JsonElement type : types) {
final JsonArray coords = type.getAsJsonArray():
}
wayPoints is a JSON object. It contains another JSON object called ship. And ship contains a JSON array called first_type. So you should get the first_type array from the ship object, and iterate on this array.
replace "" with blank.
Map<String, Object> attributes = new HashMap<String, Object>();
Set<Entry<String, JsonElement>> entrySet = jsonObject.entrySet();
for(Map.Entry<String,JsonElement> entry : entrySet){
if (! nonProperties.contains(entry.getKey())) {
properties.put(entry.getKey(), jsonObject.get(entry.getKey()).replace("\"",""));
}
}
How are you creating your JsonObject? Your code works for me. Consider this
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
...
...
...
try{
JsonObject jsonObject = new JsonObject();
jsonObject.addProperty("keyInt", 2);
jsonObject.addProperty("keyString", "val1");
jsonObject.addProperty("id", "0123456");
System.out.println("json >>> "+jsonObject);
Map<String, Object> attributes = new HashMap<String, Object>();
Set<Entry<String, JsonElement>> entrySet = jsonObject.entrySet();
for(Map.Entry<String,JsonElement> entry : entrySet){
attributes.put(entry.getKey(), jsonObject.get(entry.getKey()));
}
for(Map.Entry<String,Object> att : attributes.entrySet()){
System.out.println("key >>> "+att.getKey());
System.out.println("val >>> "+att.getValue());
}
}
catch (Exception ex){
System.out.println(ex);
}
And it is working fine. Now I am interested in knowing how you created that JSON of yours?
You can also try this (JSONObject)
import org.json.JSONObject;
...
...
...
try{
JSONObject jsonObject = new JSONObject("{\"keyInt\":2,\"keyString\":\"val1\",\"id\":\"0123456\"}");
System.out.println("JSON :: "+jsonObject.toString());
Iterator<String> it = jsonObject.keys();
while( it.hasNext() ){
String key = it.next();
System.out.println("Key:: !!! >>> "+key);
Object value = jsonObject.get(key);
System.out.println("Value Type "+value.getClass().getName());
}
}
catch (Exception ex){
System.out.println(ex);
}
JsonArray is an Iterable<JsonElement>. So you can use for in loop.
JsonObject jsonObject = new JsonParser().parse(jsonString).getAsJsonObject();
final JsonArray data = jsonObject.getAsJsonArray("data");
System.out.println("data : " + data);
System.out.println("recordsTotal : " + jsonObject.get("recordsTotal"));
List<String> list = new ArrayList<String>();
for (JsonElement element : data) {
list.add(((JsonObject) element).get("part_number").getAsString());
}
Suppose class Name for Json Model is Example.
import com.google.gson.annotations.SerializedName;
import java.util.List;
public class Example {
@SerializedName("recordsTotal")
private Integer recordsTotal;
@SerializedName("data")
private List<Datum> data = null;
public Integer getRecordsTotal() {
return recordsTotal;
}
public void setRecordsTotal(Integer recordsTotal) {
this.recordsTotal = recordsTotal;
}
public List<Datum> getData() {
return data;
}
public void setData(List<Datum> data) {
this.data = data;
}
}
And suppose List of Data class name is Datum :-
import com.google.gson.annotations.SerializedName;
import java.util.List;
public class Datum {
@SerializedName("part_number")
private String partNumber;
@SerializedName("part_type")
private String partType;
@SerializedName("id")
private Integer id;
@SerializedName("manufacturers")
private List<String> manufacturers = null;
public String getPartNumber() {
return partNumber;
}
public void setPartNumber(String partNumber) {
this.partNumber = partNumber;
}
public String getPartType() {
return partType;
}
public void setPartType(String partType) {
this.partType = partType;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public List<String> getManufacturers() {
return manufacturers;
}
public void setManufacturers(List<String> manufacturers) {
this.manufacturers = manufacturers;
}
}
And then through Gson library we can convert json to java Model :
Example example = new Gson().fromJson(jsonString, new TypeToken<Example>() {}.getType());
Now we can get list of data though example model :-
List<Datum> dataList = example.getData();
From dataList you can traverse and get all info.
If partNmber List we need then we can get in this way :-
List<String> partNumberList = new ArrayList<>();
for (Datum data : dataList) {
partNumberList.add(data.getPartNumber());
}