Java reading JSON null - java
OK, I am getting null for whatever reason I cannot fathom.
Here is my code:
import java.util.*;
import java.io.*;
import com.google.gson.*;
public class readGoogle {
public static String MapTitle;
public static Data data;
public static Item item;
public static String dan;
public static FileReader fr;
public static void main(String[] args) {
/**
try {
fr = new FileReader("map1.txt");
}catch(FileNotFoundException fne) {
fne.printStackTrace();
}
StringBuffer sb = new StringBuffer();
char[] b = new char[1000];
int n = 0;
try {
while ((n = fr.read(b)) > 0) {
sb.append(b, 0, n);
}
}catch(IOException rex) {
rex.printStackTrace();
}
String fileString = sb.toString();
**/
String json =
"{"
+"'name': 'map_one.txt',"
+"'title': 'xxx One',"
+"'currentMap': 4,"
+"'rightMap': 3,"
+"'lefttMap': 5,"
+"'downMap': 1,"
+"'upMap': 2,"
+"'items': ["
+" { name: 'Pickaxe', x: 5, y: 1 },"
+" { name: 'Battleaxe', x: 2, y: 3 }"
+"],"
+" 'map': [ [ 1,3,1,1,1,24,1,1,1,1,1,1,1 ],"
+" [ 1,3,1,1,1,24,1,1,1,1,1,1,1 ],"
+" [ 1,7,1,1,1,24,1,1,24,1,1,1,1 ],"
+" [ 1,7,1,1,7,1,1,1,24,1,1,1,1 ],"
+" [ 1,7,7,7,1,24,24,24,24,1,1,1,1 ],"
+" [ 1,1,7,1,1,24,1,24,1,1,1,1,1 ],"
+" [ 1,1,1,1,1,24,1,1,1,1,1,1,1 ],"
+" [ 1,1,3,1,1,24,1,1,1,1,1,1,1 ],"
+" [ 1,3,3,1,1,24,1,1,1,1,1,1,1 ]]"
+"};";
try {
data = new Gson().fromJson(json, Data.class);
}catch (Exception er) {
er.printStackTrace();
}
System.out.println("Name of map: " + data.getTitle());
System.out.println("File of map: " + data.getName());
System.out.println("Current Map: " + data.getCurrentMap());
System.out.println(data.getItems().get(0).getName()); // Pickaxe
}
public class Item {
public String name;
public int x;
public int y;
public String getName() { return name; }
public int getX() { return x; }
public int getY() { return y; }
public void setName(String name) { this.name = name; }
public void setX(int x) { this.x = x; }
public void setY(int y) { this.y = y; }
}
public static class Data {
private String name;
private String title;
private int currentMap;
private int leftMap;
private int rightMap;
private int upMap;
private int downMap;
private List<Item> items;
private int[][] map;
public String getName() { return name; }
public String getTitle() { return title; }
public int getCurrentMap() { return currentMap; }
public int getUpMap() { return upMap; }
public int getDownMap() { return downMap; }
public int getLeftMap() { return leftMap; }
public int getRightMap() { return rightMap; }
public List<Item> getItems() { return items; }
public int[][] getMap() { return map; }
public void setName(String name) { this.name = name; }
public void setTitle(String title) { this.title = title; }
public void setCurrentMap(int currentMap) { this.currentMap = currentMap; }
public void setItems(List<Item> items) { this.items = items; }
public void setMap(int[][] map) { this.map = map; }
}
}
public static class Item {
public static String name;
public static int x;
public int y;
public static String getName() { return name; }
public static int getX() { return x; }
public int getY() { return y; }
public void setName(String name) { this.name = name; }
public void setX(int x) { this.x = x; }
public void setY(int y) { this.y = y; }
}
public static class Data {
private String name;
private String title;
private int currentMap;
private int leftMap;
private int rightMap;
private int upMap;
private int downMap;
private List<Item> items;
private int[][] map;
public String getName() { return name; }
public String getTitle() { return title; }
public int getCurrentMap() { return currentMap; }
public int getUpMap() { return upMap; }
public int getDownMap() { return downMap; }
public int getLeftMap() { return leftMap; }
public int getRightMap() { return rightMap; }
public List<Item> getItems() { return items; }
public int[][] getMap() { return map; }
public void setName(String name) { this.name = name; }
public void setTitle(String title) { this.title = title; }
public void setCurrentMap(int currentMap) { this.currentMap = currentMap; }
public void setItems(List<Item> items) { this.items = items; }
public void setMap(int[][] map) { this.map = map; }
}
}
Here is the output:
com.google.gson.JsonParseException: The JsonDeserializer com.google.gson.Default
TypeAdapters$CollectionTypeAdapter#6016a786 failed to deserialized json object [
{"name":"Pickaxe","x":5,"y":1},{"name":"Battleaxe","x":2,"y":3}] given the type
com.google.gson.ParameterizedTypeImpl#6c59096e
at com.google.gson.JsonDeserializerExceptionWrapper.deserialize(JsonDese
rializerExceptionWrapper.java:63)
at com.google.gson.JsonDeserializationVisitor.invokeCustomDeserializer(J
sonDeserializationVisitor.java:88)
at com.google.gson.JsonObjectDeserializationVisitor.visitFieldUsingCusto
mHandler(JsonObjectDeserializationVisitor.java:117)
at com.google.gson.ObjectNavigator.navigateClassFields(ObjectNavigator.j
ava:150)
at com.google.gson.ObjectNavigator.accept(ObjectNavigator.java:123)
at com.google.gson.JsonDeserializationContextDefault.fromJsonObject(Json
DeserializationContextDefault.java:73)
at com.google.gson.JsonDeserializationContextDefault.deserialize(JsonDes
erializationContextDefault.java:51)
at com.google.gson.Gson.fromJson(Gson.java:495)
at com.google.gson.Gson.fromJson(Gson.java:444)
at com.google.gson.Gson.fromJson(Gson.java:396)
at com.google.gson.Gson.fromJson(Gson.java:372)
at readGoogle.main(readGoogle.java:62)
Caused by: java.lang.RuntimeException: No-args constructor for class readGoogle$
Item does not exist. Register an InstanceCreator with Gson for this type to fix
this problem.
at com.google.gson.MappedObjectConstructor.constructWithNoArgConstructor
(MappedObjectConstructor.java:64)
at com.google.gson.MappedObjectConstructor.construct(MappedObjectConstru
ctor.java:53)
at com.google.gson.JsonObjectDeserializationVisitor.constructTarget(Json
ObjectDeserializationVisitor.java:41)
at com.google.gson.JsonDeserializationVisitor.getTarget(JsonDeserializat
ionVisitor.java:56)
at com.google.gson.ObjectNavigator.accept(ObjectNavigator.java:101)
at com.google.gson.JsonDeserializationContextDefault.fromJsonObject(Json
DeserializationContextDefault.java:73)
at com.google.gson.JsonDeserializationContextDefault.deserialize(JsonDes
erializationContextDefault.java:51)
at com.google.gson.DefaultTypeAdapters$CollectionTypeAdapter.deserialize
(DefaultTypeAdapters.java:472)
at com.google.gson.DefaultTypeAdapters$CollectionTypeAdapter.deserialize
(DefaultTypeAdapters.java:435)
at com.google.gson.JsonDeserializerExceptionWrapper.deserialize(JsonDese
rializerExceptionWrapper.java:50)
... 11 more
Exception in thread "main" java.lang.NullPointerException
at readGoogle.main(readGoogle.java:67)
Press any key to continue . . .
Something is wrong within the Items json array... :S
are you sure the property 'name' of Item should be static? Doesn't seem right to me....
edit -- and the property 'x'
edit -- if you look at your stack trace, it says
Caused by: java.lang.RuntimeException: No-args constructor for class readGoogle$
Item does not exist.
So you need to provide a constructor that is public and takes no arguments.
I had a similar problem and solved it by reading the documentation http://sites.google.com/site/gson/gson-user-guide on nested inner classes. You need to define your items class as a nested class of data and declare it as static, with an empty constructor.
Related
How do I leverage a json mapping file to convert from one pojo to another pojo?
I have two POJOs (Person.java and User.java) that contain similar information. See below: public class Person { private String first_name; private String last_name; private Integer age; private Integer weight; private Integer height; public String getFirst_name() { return first_name; } public void setFirst_name(String first_name) { this.first_name = first_name; } public String getLast_name() { return last_name; } public void setLast_name(String last_name) { this.last_name = last_name; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } public Integer getWeight() { return weight; } public void setWeight(Integer weight) { this.weight = weight; } public Integer getHeight() { return height; } public void setHeight(Integer height) { this.height = height; } } public class User { private String name_first; private String name_last; private Integer my_age; private Integer my_weight; private String social_security; public String getName_first() { return name_first; } public void setName_first(String name_first) { this.name_first = name_first; } public String getName_last() { return name_last; } public void setName_last(String name_last) { this.name_last = name_last; } public Integer getMy_age() { return my_age; } public void setMy_age(Integer my_age) { this.my_age = my_age; } public Integer getMy_weight() { return my_weight; } public void setMy_weight(Integer my_weight) { this.my_weight = my_weight; } public String getSocial_security() { return social_security; } public void setSocial_security(String social_security) { this.social_security = social_security; } } I have defined a mapping.json file as shown below using GSON. { "columnMap": [ { "userColumn": "name_first", "personColumn": "first_name" }, { "userColumn": "last_first", "personColumn": "first_last" }, { "userColumn": "my_age", "personColumn": "age" }, { "userColumn": "my_weight", "personColumn": "weight" } ] } public class Mapping { private ArrayList<Pair> columnMap; public Mapping(){ columnMap = new ArrayList<>(); } public ArrayList<Pair> getColumnMap() { return columnMap; } public void setColumnMap(ArrayList<Pair> columnMap) { this.columnMap = columnMap; } } I am writing a utility class helper function that converts between a Person and User object the mapped pairs. public class Pair { private String userColumn; private String personColumn; public String getUserColumn() { return userColumn; } public void setUserColumn(String userColumn) { this.userColumn = userColumn; } public String getPersonColumn() { return personColumn; } public void setPersonColumn(String personColumn) { this.personColumn = personColumn; } public static void main(String args[]){ } } My question is below: As you can see the returnVal object is being set by me (the programmer) to convert from a User POJO to a Person POJO. How do I leverage the pre-defined mapping.json to do this? The reason I am asking is in the future, the mapping.json file may change (maybe the weight mapping no longer exists). So I am trying to avoid re-programming this Utility.userToPerson() function. How can I achieve this? I am thinking Java reflection is the way to go, but I would like to hear back from the Java community. public class Utility { public static Person userToPerson(User u){ Person returnVal = new Person(); returnVal.setAge(u.getMy_age()); // <-- Question How do I leverage mapping.json here? returnVal.setFirst_name(u.getName_first()); returnVal.setLast_name(u.getName_last()); returnVal.setWeight(u.getMy_weight()); return returnVal; } }
You can introspect the beans (i.e. User and Person) for the field names and call corresponding getter from User to fetch the value. Later call corresponding setter in Person. Here I have taken userToPersonFieldsMap for mapping the field, you can load mapping from JSON file and construct the map accordingly. Important code section is the for loop, where it dynamically calls getter and setter and does the job. import java.beans.IntrospectionException; import java.beans.PropertyDescriptor; import java.lang.reflect.InvocationTargetException; import java.util.HashMap; import java.util.Map; public class UserToPersonMapper { public static void main(String[] args) throws IntrospectionException, InvocationTargetException, IllegalAccessException { Map<String, String> userToPersonFieldsMap = new HashMap<>(); userToPersonFieldsMap.put("name_first", "first_name"); userToPersonFieldsMap.put("last_first", "first_last"); userToPersonFieldsMap.put("age", "personAge"); //existing user User user = new User("Tony", "Stark", 20); //new person - to be initialised with values from user Person person = new Person(); for (Map.Entry<String, String> entry : userToPersonFieldsMap.entrySet()) { Object userVal = new PropertyDescriptor(entry.getKey(), User.class).getReadMethod().invoke(user); new PropertyDescriptor(entry.getValue(), Person.class).getWriteMethod().invoke(person, userVal); } System.out.println(user); System.out.println(person); } } class User { private String name_first; private String last_first; private int age; public User(String name_first, String last_first, int age) { this.name_first = name_first; this.last_first = last_first; this.age = age; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getName_first() { return name_first; } public String getLast_first() { return last_first; } public void setName_first(String name_first) { this.name_first = name_first; } public void setLast_first(String last_first) { this.last_first = last_first; } #Override public String toString() { return "User{" + "name_first='" + name_first + '\'' + ", last_first='" + last_first + '\'' + ", age=" + age + '}'; } } class Person { private String first_name; private String first_last; private int personAge; public void setFirst_name(String first_name) { this.first_name = first_name; } public void setFirst_last(String first_last) { this.first_last = first_last; } public String getFirst_name() { return first_name; } public String getFirst_last() { return first_last; } public int getPersonAge() { return personAge; } public void setPersonAge(int personAge) { this.personAge = personAge; } #Override public String toString() { return "Person{" + "first_name='" + first_name + '\'' + ", first_last='" + first_last + '\'' + ", personAge=" + personAge + '}'; } } You can tweak and try it out this example to make it more align with your requirement. Note: This solution uses reflection.
Parsing Json Response sent from Google Distance Matrix API
This json occurs when a destination or origin is outside of the uk, therefore not giving me any results! I need to check for this for a null check so i dont receive null pointer exception JSON RESULT: { "destination_addresses" : [ "Durham, NC, USA" ], "origin_addresses" : [ "Lancashire, UK" ], "rows" : [ { "elements" : [ { "status" : "ZERO_RESULTS" } ] } ], "status" : "OK" } Code: public static void extractJsonFromRequest(GoogleResponsePojo response) { String destinationAddress = response.getDestination_addresses().get(0); String timeTaken = response.getRows().get(0).getElements().get(0).getDuration().getText(); String originAddress = response.getOrigin_addresses().get(0); System.out.println("It will take ** "+ timeTaken + " ** to walk from " + originAddress + " to " + destinationAddress); } Google Reponse POJO which is structure of json: public class GoogleResponsePojo { private List<String> destination_addresses; private List<String> origin_addresses; private List<Rows> rows; public List<String> getDestination_addresses() { return destination_addresses; } public void setDestination_addresses(List<String> destination_addresses) { this.destination_addresses = destination_addresses; } public List<String> getOrigin_addresses() { return origin_addresses; } public void setOrigin_addresses(List<String> origin_addresses) { this.origin_addresses = origin_addresses; } public List<Rows> getRows() { return rows; } public void setRows(List<Rows> rows) { this.rows = rows; } } class Rows { private List<Element> elements; public List<Element> getElements() { return elements; } public void setElements(List<Element> elements) { this.elements = elements; } } class Element { private TextValue distance; private TextValue duration; public TextValue getDistance() { return distance; } public void setDistance(TextValue distance) { this.distance = distance; } public TextValue getDuration() { return duration; } public void setDuration(TextValue duration) { this.duration = duration; } } class TextValue { private String text; private String value; public String getText() { return text; } public void setText(String text) { this.text = text; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } } I essentially need to just parse the json below so that i can say (if status != ZERO_RESULTS ) save the response else throw an exception! Probably easy but im struggling! Thanks so much!
Change GoogleResponsePojo to: public class GoogleResponsePojo { private List<String> destination_addresses; private List<String> origin_addresses; private List<Rows> rows; public void setDestination_addresses(List<String> destination_addresses) { this.destination_addresses = destination_addresses; } public void setOrigin_addresses(List<String> origin_addresses) { this.origin_addresses = origin_addresses; } public void setRows(List<Rows> rows) { this.rows = rows; } //getters } private static class Rows{ private List<Element> elements; public void setElements(List<Element> elements) { this.elements = elements; } //getters } private static class Element{ private TextValue distance; private TextValue duration; public void setDistance(TextValue distance) { this.distance = distance; } public void setDuration(TextValue duration) { this.duration = duration; } //getters } private static class TextValue{ private String text; private String value; public void setText(String text) { this.text = text; } public void setValue(String value) { this.value = value; } //getters } You can take duration as following: GoogleResponsePojo name = gson.fromJson(response.toString(),GoogleResponsePojo.class); name.getRows().get(0).getDuration().getText(); And I recommend use http-request built on apache http api. Its simple to use: public static final String BASE_URL = "https://maps.googleapis.com/maps/api/distancematrix/json"; private static final HttpRequest<GoogleResponsePojo> HTTP_REQUEST = HttpRequestBuilder.createGet(BASE_URL, GoogleResponsePojo.class) .addDefaultRequestParameter("origins", "Seattle") .addDefaultRequestParameter("destinations", "San+Francisco") .addDefaultRequestParameter("key", "***") .build(); #GET #Produces(MediaType.APPLICATION_JSON) public static void updateTestExecutionDetails() throws IOException { ResponseHandler<GoogleResponsePojo> responseHandler = HTTP_REQUEST.execute(); GoogleResponsePojo name = responseHandler.orElseThrow(); // throws ResponseException when status code != 200 System.out.println(name.getDestination_addresses().get(0)); System.out.println(name.getRows().get(0).getElements().get(0).getDuration().getText()); System.out.println(name.getOrigin_addresses().get(0)); }
Created add() method to insert objects into an array and all i get are null values
this is a class called Doglist to add the object to an array. public class DogList { private int numItems; private DogItem[] dogListArray; private int position; DogList () { numItems=0; position = 0; dogListArray = new DogItem[10]; } public void add (DogItem item) { dogListArray[numItems++]= new DogItem(item.getName(), item.getBreed(), item.getWeight(), item.getOwner1(), item.getOwner2() ); } public String toString() { String result = ""; for (int i=0; i<numItems; i++) { result += dogListArray[i].toString() + "\n"; } return result; } public DogItem searchForDogItem (DogItem gi) { System.out.println("Here is your obj value: " + gi ); return null; }//This is the one im having trouble with. } I have all the setters and getters in the DogItem class. and this is from the UI where i get the dog info(name, breed, weight, owners1&2 names) public void searchForItem (String name ) { DogItem gi = new DogItem (name); gi = gl.searchForDogItem(gi); if (gi==null) { msgTextField.setText("Dog Not Found"); } else { nameTextField.setText(String.valueOf(gi.getName())); breedTextField.setText(String.valueOf(gi.getBreed())); weightTextField.setText(String.valueOf(gi.getWeight())); owner1TextField.setText(String.valueOf(gi.getOwner1())); owner2TextField.setText(String.valueOf(gi.getOwner2())); } } Ill try and clear things up as i go. this is the output i get Here is your obj value: null null 0.0 null null
Ok so here is what it probably should look like instead. Just from what I saw wrong already. However you'd probably want to override the toString() method of DogItem. Main method example of this: public class Main { public static void main(String[] args) { DogItem dogItem = new DogItem("Spot", "Dalmation", "45", "Bob", "Sandy"); DogItem.add(dogItem); DogItem result = DogItem.searchForItem("Spot"); if (result == null) { System.out.println("Dog not found"); // GUI error output goes here } else { System.out.println("Here is your obj value: " + result); // Where your GUI stuff goes } } } DogItem example of this: public class DogItem { private static DogItem[] dogListArray = new DogItem[100]; private static int numItems = 0; private String name; private String breed; private String weight; private String owner1; private String owner2; public DogItem(String name, String breed, String weight, String owner1, String owner2) { this.name = name; this.breed = breed; this.weight = weight; this.owner1 = owner1; this.owner2 = owner2; } public static void add(DogItem dogItem) { dogListArray[numItems++] = dogItem; } public static DogItem searchForItem(String name) { DogItem dogItem = null; for (DogItem result : dogListArray) { if (result != null) { if (result.getName() == name) { dogItem = result; } } } return dogItem; } #Override public String toString() { String result = name + ", " + breed + ", " + weight + ", " + owner1 + " " + owner2; return result; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getBreed() { return breed; } public void setBreed(String breed) { this.breed = breed; } public String getWeight() { return weight; } public void setWeight(String weight) { this.weight = weight; } public String getOwner1() { return owner1; } public void setOwner1(String owner1) { this.owner1 = owner1; } public String getOwner2() { return owner2; } public void setOwner2(String owner2) { this.owner2 = owner2; } } These would be recommended changes from me though: private static ArrayList<String> owners; private static ArrayList<DogItem> dogsList; public DogItem(String name, String breed, String weight, String owner) { this.name = name; this.breed = breed; this.weight = weight; this.owners.add(owner); } public void init() { owners = new ArrayList<String>(); dogsList = new ArrayList<DogItem>(); } public void addDog(DogItem dogItem) { dogsList.add(dogItem); } public DogItem searchForItem(String name) { DogItem dogItem = null; for (DogItem result : dogsList) { if (result != null) { if (result.getName() == name) { dogItem = result; } } } return dogItem; } public void addOwner(String owner) { owners.add(owner); } public String getOwner() { return owners.get(owners.size() - 1); }
Adding Items to my inventory in Java
I am making a text-based game on JavaFX, and after I hit a tree, I want to get Oak logs. I have already built my inventory, and I have put default items in it such as Water, Bread, etc. I am trying to add my Oak Logs to my inventory, but nothing is working. Here is a part of my code: Item ItemList[] = {new Bread(), new OakLog()}; Optional<ButtonType> result = alert.showAndWait(); if(result.get() == buttonTypeOak) { woodcuttingXP = woodcuttingXP + oakXP; dialogue.appendText("You swing at an Oak tree. + " + oakXP + "XP.\n"); dialogue.appendText("You gathered 1 log.\n"); mainCharacter.getInventory().add(new OakLog()); } Here is my Item Class: package game; public class Item { private String name; private int weight; private int quantity; private int value; private String description; public Item(String name, int value, String description) { this.name = name; this.value = value; this.description = description; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getWeight() { return weight; } public void setWeight(int weight) { this.weight = weight; } public int getQuantity() { return quantity; } public void setQuantity(int quantity) { this.quantity = quantity; } public int getValue() { return value; } public void setValue(int value) { this.value = value; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String toString() { return getName(); } } And finally, here is my Character class: package game; import java.util.ArrayList; import beverages.Water; import items.OakLog; import rawFood.Bread; public class Character { private String name; private int hydrationLevel; private int healthLevel; private int hungerLevel; private int woodcuttingLevel; public int getWoodcuttingLevel() { return woodcuttingLevel; } public void setWoodcuttingLevel(int woodcuttingLevel) { this.woodcuttingLevel = woodcuttingLevel; } public int getHungerLevel() { return hungerLevel; } public void setHungerLevel(int hungerLevel) { this.hungerLevel = hungerLevel; } private ArrayList<Item> inventory = new ArrayList<Item>(); public ArrayList<Item> getInventory() { return inventory; } public void setInventory(ArrayList<Item> inventory) { this.inventory = inventory; } //creates a person with two basic items public Character(String name){ this.name = name; this.hydrationLevel = 100; this.healthLevel = 100; this.hungerLevel = 100; this.woodcuttingLevel = 1; addToInventory (new Bread()); addToInventory (new OakLog()); addToInventory (new Water()); } //GETTERS AND SETTERS public String getName() { return name; } public int getHydrationLevel() { return hydrationLevel; } public void setHydrationLevel(int hydrationLevel) { this.hydrationLevel = hydrationLevel; } public int getHealthLevel() { return healthLevel; } public void setHealthLevel(int healthLevel) { this.healthLevel = healthLevel; } //END GETTERS AND SETTERS /*Method Name: eat() *Method Inputs: a piece of food *Method Purpose: Will allow the user to eat food */ public Item getItemFromInventory(int index){ Item item = inventory.get(index); return item; } public void addToInventory(Item item){ if(inventory.contains(item)){ item.setQuantity(item.getQuantity()+1); } else{ item.setQuantity(1); inventory.add(item); } } public String toString(){ return "Character Stats:\nName:" + getName() + "\nHydration: " + getHydrationLevel() + "\nHealth: " + getHealthLevel() + "\nWoodcutting: " + getWoodcuttingLevel(); } }
In your code, you have: if(inventory.contains(item)){ item.setQuantity(item.getQuantity()+1); } This just updates the quantity of the local variable item in the method, not the item in the inventory.
how to read json data of type linkedtreemap [GSON]?
I am trying to read the below json data. How to read using LinkedTreeMap? {"msgType": "gameInit", "data": { "race": { "track": { "id": "indianapolis", "name": "Indianapolis", "pieces": [ { "length": 100.0 }, { "length": 100.0, "switch": true }, { "radius": 200, "angle": 22.5 } ], "lanes": [ { "distanceFromCenter": -20, "index": 0 }, { "distanceFromCenter": 0, "index": 1 }, { "distanceFromCenter": 20, "index": 2 } ], "startingPoint": { "position": { "x": -340.0, "y": -96.0 }, "angle": 90.0 } }, "cars": [ { "id": { "name": "Schumacher", "color": "red" }, "dimensions": { "length": 40.0, "width": 20.0, "guideFlagPosition": 10.0 } }, { "id": { "name": "Rosberg", "color": "blue" }, "dimensions": { "length": 40.0, "width": 20.0, "guideFlagPosition": 10.0 } } ], "raceSession": { "laps": 3, "maxLapTimeMs": 30000, "quickRace": true } } }}
I've little long but working approach to parse your JSON Object using Gson. You can try it as following: import com.google.gson.Gson; public class JsonParser { public static void main(String[] args){ Gson gson = new Gson(); String yourJson = ""; MainObject object = gson.fromJson(yourJson, MainObject.class); } } Here yourJson is your JSON object in which your response is received, here I've used String just to show you. And MainObject is the POJO for required to parse your JSON object. I've shown all POJOs for that are required for your JSON. Try to use it. MainObject.java public class MainObject { private String msgType; private Data data; public String getMsgType() { return msgType; } public void setMsgType(String msgType) { this.msgType = msgType; } public Data getData() { return data; } public void setData(Data data) { this.data = data; } } Data.java public class Data { private race race; public race getRace() { return race; } public void setRace(race race) { this.race = race; } } Track.java public class Track{ private String id; private String name; private List<Pieces> pieces; private List<Lanes> lanes; private startingPoint startingPoint; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public List<Pieces> getPieces() { return pieces; } public void setPieces(List<Pieces> pieces) { this.pieces = pieces; } public List<Lanes> getLanes() { return lanes; } public void setLanes(List<Lanes> lanes) { this.lanes = lanes; } public startingPoint getStartingPoint() { return startingPoint; } public void setStartingPoint(startingPoint startingPoint) { this.startingPoint = startingPoint; } } Pieces.java public class Pieces{ private int length; private boolean switch; private int radius; private float angle; public int getLength() { return length; } public void setLength(int length) { this.length = length; } public int getRadius() { return radius; } public void setRadius(int radius) { this.radius = radius; } public float getAngle() { return angle; } public void setAngle(float angle) { this.angle = angle; } public boolean isSwitch() { return Switch; } public void setSwitch(boolean _switch) { Switch = _switch; } } Lanes.java public class Lanes{ private String distanceFromCenter; private int index; public String getDistanceFromCenter() { return distanceFromCenter; } public void setDistanceFromCenter(String distanceFromCenter) { this.distanceFromCenter = distanceFromCenter; } public int getIndex() { return index; } public void setIndex(int index) { this.index = index; } } StartingPoint.java public class StartingPoint{ private String angle; private Position position; public String getAngle() { return angle; } public void setAngle(String angle) { this.angle = angle; } public Position getPosition() { return position; } public void setPosition(Position position) { this.position = position; } } Position.java public class Position{ private String x; private String y; public String getX() { return x; } public void setX(String x) { this.x = x; } public String getY() { return y; } public void setY(String y) { this.y = y; } } Cars.java public class Cars{ private Id id; private Dimensions dimensions; public id getId() { return id; } public void setId(id id) { this.id = id; } public Dimensions getDimensions() { return dimensions; } public void setDimensions(Dimensions dimensions) { this.dimensions = dimensions; } } Id.java public class Id{ private String name; private String color; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getColor() { return color; } public void setColor(String color) { this.color = color; } } Dimensions.java public class Dimensions{ private int length; private int width; private int guideFlagPosition; public int getLength() { return length; } public void setLength(int length) { this.length = length; } public int getWidth() { return width; } public void setWidth(int width) { this.width = width; } public int getGuideFlagPosition() { return guideFlagPosition; } public void setGuideFlagPosition(int guideFlagPosition) { this.guideFlagPosition = guideFlagPosition; } } RaceSession.java public class RaceSession{ private int lap; private String maxLapTimeMs; private boolean quickRace; public int getLap() { return lap; } public void setLap(int lap) { this.lap = lap; } public String getMaxLapTimeMs() { return maxLapTimeMs; } public void setMaxLapTimeMs(String maxLapTimeMs) { this.maxLapTimeMs = maxLapTimeMs; } public boolean isQuickRace() { return quickRace; } public void setQuickRace(boolean quickRace) { this.quickRace = quickRace; } } That's all. All required POJOs are here. I've used this approach and it's working fine.
From the site: public static void main(String[] args) { Gson gson = new Gson(); try { System.out.println("Reading JSON from a file"); System.out.println("----------------------------"); BufferedReader br = new BufferedReader( new FileReader(args[0])); //convert the json string back to object MyBean countryObj = gson.fromJson(br, MyBean.class); // MyBean contains the data in the JSON and is a standard Java Bean } }
BufferedReader in = new BufferedReader(input); String inputLine; String fullline = ""; while ((inputLine = in.readLine()) != null) { fullline = fullline.concat(inputLine); } JSONObject rootObject = new JSONObject(fullline); JSONObject rows1 = rootObject.getJSONObject("data"); JSONObject race = rows1.getJSONObject("race"); JSONObject track = rows1.getJSONObject("track"); JSONArray pieces = rows1.getJSONArray("pieces");
Hello This is simple you can do using JSON there is no need to use external library Gson.it can also increase the your app size.so avoid to use it. // Try to parse JSON try { JSONObject jsonObjMain = new JSONObject(myjsonstring); JSONObject jsonObjectData=(JSONObject) jsonObjMain.get("data"); JSONObject jsonObjectRace=(JSONObject) jsonObjectData.get("race"); JSONObject jsonObjectTrack=(JSONObject) jsonObjectRace.get("track"); JSONArray jsonArrayPieces=(JSONArray) jsonObjectTrack.get("pieces"); JSONArray jsonArrayLanes=(JSONArray) jsonObjectTrack.get("lanes"); JSONObject jsonObjectStartingPoint=(JSONObject) jsonObjectTrack.get("startingPoint"); System.out.println("Starting Point :"+jsonObjectStartingPoint); JSONArray jsonArrayCars=(JSONArray) jsonObjectRace.get("cars"); JSONObject jsonObjectRaceSession=(JSONObject) jsonObjectRace.get("raceSession"); System.out.println("Race Session :"+jsonObjectRaceSession); for (int i = 0; i < jsonArrayCars.length(); i++) { JSONObject jsonObj = jsonArrayCars.getJSONObject(i); JSONObject jsonObjId = (JSONObject) jsonObj.get("id"); System.out.println("id :"+jsonObjId); JSONObject jsonObjDimensions = (JSONObject) jsonObj.get("dimensions"); System.out.println("Dinmentions :"+jsonObjDimensions); } for (int i = 0; i < jsonArrayPieces.length(); i++) { JSONObject jsonObj = jsonArrayPieces.getJSONObject(i); System.out.println("Piece data :"+jsonObj); } for (int i = 0; i < jsonArrayLanes.length(); i++) { JSONObject jsonObj = jsonArrayLanes.getJSONObject(i); System.out.println("Lanes data :"+jsonObj); } } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); }