Class contains all the songs
public class Songs{
private List levels;
public List getLevels() {
return levels;
}
public void setLevels(List levels) {
this.levels = levels;
}
}
each song object
public class Levels{
private Number id;
private String name;
private List sequence;
public Number getId(){
return this.id;
}
public void setId(Number id){
this.id = id;
}
public String getName(){
return this.name;
}
public void setName(String name){
this.name = name;
}
public List getSequence() {
return sequence;
}
public void setSequence(List sequence) {
this.sequence = sequence;
}
}
JSON
{
"levels": [
{
"id": 1,
"name": "Sequence",
"sequence": [
17,
1,
2
]
},
{
"id": 2,
"name": "Sequence",
"sequence": [
17,
0,
1,
2,
4,
4,
5,
6
]
}
]
}
Java code
This works if I debug I can see the objects but the problem is getting sequence the array of int. Can Anyone help me ??? I can paste the stack trace if I do list2.getLevels().get(0).getSequence();
String json = new String(b);
Gson gson = new Gson();
Songs list2 = (Songs) gson.fromJson(json, Songs.class);
//I CAN READ ONE LEVEL LIKE THIS
LinkedTreeMap<String,Levels> l = (LinkedTreeMap)songs.getLevels().get(0);
//HOW CAN I GET SEQUENCE ARRAY???
Levels.java
import java.util.List;
public class Levels {
private Number id;
private String name;
private List sequence;
public Number getId(){
return this.id;
}
public void setId(Number id){
this.id = id;
}
public String getName(){
return this.name;
}
public void setName(String name){
this.name = name;
}
public List getSequence() {
return sequence;
}
public void setSequence(List sequence) {
this.sequence = sequence;
}
}
Songs.java
import java.util.List;
public class Songs{
private List<Levels> levels;
public List<Levels> getLevels() {
return levels;
}
public void setLevels(List<Levels> levels) {
this.levels = levels;
}
}
and use this to get the sequence list:
String json = new String("{\n \"levels\": [\n {\n \"id\": 1,\n \"name\": \"Sequence\",\n \"sequence\": [\n 17,\n 1,\n 2\n ]\n },\n {\n \"id\": 2,\n \"name\": \"Sequence\",\n \"sequence\": [\n 17,\n 0,\n 1,\n 2,\n 4,\n 4,\n 5,\n 6\n ]\n }\n ]\n}");
Gson g = new Gson();
Songs vc = (Songs)g.fromJson(json, Songs.class);
List test = vc.getLevels().get(0).getSequence();
I'm going to paste a sample that I created but stored in shared preferences.
SharedPreferences settings = getSharedPreferences(String name, MODE_MULTI_PROCESS);
SharedPreferences.Editor editor = settings.edit();
Gson gson = new Gson();
String json = gson.toJson(ArrayList<Object>);
editor.putString("list", json);
editor.commit();
And then when I want to read this Json I just do:
SharedPreferences settings = getSharedPreferences(String name, MODE_MULTI_PROCESS);
String shared = settings.getString("list", null);
Gson gson = new Gson();
ArrayList<Object> temp = gson.fromJson(shared, new TypeToken<ArrayList<Object>>(){}.getType());
Related
I'm trying to obtain an ArrayList of object and initialize it in a wrapper class,
this is my request;
RestTemplate restTemplate = new RestTemplate();
Inventory i = restTemplate.getForObject("http://localhost:8082/items",Inventory.class);
my response handler;
#RequestMapping(value ="/items", method = RequestMethod.GET)
public ArrayList<Item> getItems() {
return ItemList.getItemList();
}
my ItemList class,
public class ItemList{
//to keep a list of globally available list of orders with the type Item.class objects
private static ArrayList<Item> itemList;
public static ArrayList<Item> getItemList() {
return itemList;
}
public static void setItemList(ArrayList<Item> itemList) {
ItemList.itemList = itemList;
}
public static Item getItemById(String id) throws NoSuchItem {
ArrayList<Item> temp = ItemList.getItemList();
for(Item x:temp){
if(x.getId().equals(id))
return x;
}
throw new NoSuchItem();
}
};
My Inventory class,
public class Inventory{
private ArrayList<Item> itemList;
public ArrayList<Item> getRandomList(int size) {
ArrayList<Item> items = new ArrayList<Item>();
ArrayList<Item> temp = this.itemList;
if(size>=itemList.size()){
return itemList;
}
else{
Random rand = new Random();
for(int i=0;i<size;i++){
int j = rand.nextInt(temp.size());
Item random = temp.get(j);
random.generateQuantity();
items.add(random);
temp.remove(random);
}
}
return items;
}
public ArrayList<Item> getItemList() {
return itemList;
}
public void setItemList(ArrayList<Item> itemList) {
this.itemList = itemList;
}
};
and finally my Item class,
public class Item {
private String name ;
private String supplier ;
private String weight;
private String id ;
private String location = "not assigned" ;
private int quantity;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSupplier() {
return supplier;
}
public void setSupplier(String supplier) {
this.supplier = supplier;
}
public String getWeight() {
return weight;
}
public void setWeight(String weight) {
this.weight = weight;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
public int getQuantity() {
return quantity;
}
public void generateQuantity(){
Random rand = new Random();
int i = rand.nextInt(100);
if(i<3){
this.quantity = 3;
}
else if(i<33){
this.quantity = 2;
}
else{
this.quantity = 1;
}
}
};
I'm building a microservice project using springboot, my response and ItemList class exist in one service , request and Inventory in the next service and the Item class on both the services, But when i run the method i get an JSON parse error: Cannot deserialize instance of ServiceA.Inventory out of START_ARRAY token, What am i doing wrong here?
PS - a sample response the /items endpoint returns ,
[
{
"name": "Mars",
"supplier": "Nestle",
"weight": "1",
"id": "mars",
"location": "not asssigned"
},
{
"name": "Kit Kat",
"supplier": "Nestle",
"weight": "1",
"id": "kitkat",
"location": "not asssigned"
},
{
"name": "Double Decker",
"supplier": "Nestle",
"weight": "1",
"id": "dd",
"location": "not asssigned"
}
]
According to yout JSON there is no Inventory in the response. So when you do this:
Inventory i = restTemplate.getForObject("http://localhost:8082/items", Inventory.class);
it complains because your response actually has an array (or list) of Item. Object inventory cannot be instantiated from an arrray. Try this:
Item[] items = restTemplate.getForObject("http://localhost:8082/items", Item[].class);
and it should work.
To have class Inventory deserialized your JSON response should be something like:
{
itemList: [
{
"name": "Mars",
"supplier": "Nestle",
"weight": "1",
"id": "mars",
"location": "not asssigned"
},
...
]
}
But note: There is also a problem with your ItemList. Anyway that is another topic because you should first think whhether your response JSON is ok or not.
I think you need to add a no args constructor to the Item class.
I have in a rest response this json:
{
"TRANS": {
"HPAY": [
{
"ID": "1234",
"DATE": "10/09/2011 18:09:27",
"REC": "wallet Ricaricato",
"COM": "Tasso Commissione",
"MSG": "Commento White Brand",
"STATUS": "3",
"EXTRA": {
"IS3DS": "0",
"CTRY": "FRA",
"AUTH": "455622"
},
"INT_MSG": "05-00-05 ERR_PSP_REFUSED",
"MLABEL": "IBAN",
"TYPE": "1"
}
]
}
}
I have made pojo class to map this json in java.
public class Trans {
private List<Hpay> hpay;
public Trans(){
}
//getter and setter
}
public class Hpay {
private String id;
private String date;
private String com;
private String msg;
private String status;
private List<Extra> extra;
private String int_msg;
private String mlabel;
private String type;
public Hpay(){
}
//getter and setter
}
I try to map the object with Gson library.
Gson gson=new Gson();
Trans transaction=gson.fromJson(response.toString(), Trans.class);
If i call hpay method on transaction i have null..i don't know why...
I have deleted previous answer and add new one as par your requirement
JSON String :
{
"TRANS": {
"HPAY": [{
"ID": "1234",
"DATE": "10/09/2011 18:09:27",
"REC": "wallet Ricaricato",
"COM": "Tasso Commissione",
"MSG": "Commento White Brand",
"STATUS": "3",
"EXTRA": {
"IS3DS": "0",
"CTRY": "FRA",
"AUTH": "455622"
},
"INT_MSG": "05-00-05 ERR_PSP_REFUSED",
"MLABEL": "IBAN",
"TYPE": "1"
}
]
}
}
Java Objects : (Here Extra is not list)
public class MyObject {
#SerializedName("TRANS")
#Expose
private Trans trans;
public Trans getTRANS() {return trans;}
public void setTRANS(Trans trans) {this.trans = trans;}
}
public class Trans {
#SerializedName("HPAY")
#Expose
private List<HPay> hPay;
public List<HPay> getHPAY() {return hPay;}
public void setHPAY(List<HPay> hPay) {this.hPay = hPay;}
}
public class HPay {
#SerializedName("ID")
#Expose
private String id;
#SerializedName("DATE")
#Expose
private String date;
#SerializedName("REC")
#Expose
private String rec;
#SerializedName("COM")
#Expose
private String com;
#SerializedName("MSG")
#Expose
private String msg;
#SerializedName("STATUS")
#Expose
private String status;
#SerializedName("EXTRA")
#Expose
private Extra extra;
#SerializedName("INT_MSG")
#Expose
private String intMsg;
#SerializedName("MLABEL")
#Expose
private String mLabel;
#SerializedName("TYPE")
#Expose
private String type;
public String getID() {return id;}
public void setID(String id) {this.id = id;}
public String getDATE() {return date;}
public void setDATE(String date) {this.date = date;}
public String getREC() {return rec;}
public void setREC(String rec) {this.rec = rec;}
public String getCOM() {return com;}
public void setCOM(String com) {this.com = com;}
public String getMSG() {return msg;}
public void setMSG(String msg) {this.msg = msg;}
public String getSTATUS() {return status;}
public void setSTATUS(String status) {this.status = status;}
public Extra getEXTRA() {return extra;}
public void setEXTRA(Extra extra) {this.extra = extra;}
public String getINTMSG() {return intMsg;}
public void setINTMSG(String intMsg) {this.intMsg = intMsg;}
public String getMLABEL() {return mLabel;}
public void setMLABEL(String mLabel) {this.mLabel = mLabel;}
public String getTYPE() {return type;}
public void setTYPE(String type) {this.type = type;}
}
public class Extra {
#SerializedName("IS3DS")
#Expose
private String is3ds;
#SerializedName("CTRY")
#Expose
private String ctry;
#SerializedName("AUTH")
#Expose
private String auth;
public String getIS3DS() { return is3ds; }
public void setIS3DS(String is3ds) { this.is3ds = is3ds; }
public String getCTRY() { return ctry; }
public void setCTRY(String ctry) { this.ctry = ctry; }
public String getAUTH() { return auth; }
public void setAUTH(String auth) { this.auth = auth; }
}
Conversion Logic :
import com.google.gson.Gson;
public class NewClass {
public static void main(String[] args) {
Gson g = new Gson();
g.fromJson(json, MyObject.class);
}
static String json = "{ \"TRANS\": { \"HPAY\": [{ \"ID\": \"1234\", \"DATE\": \"10/09/2011 18:09:27\", \"REC\": \"wallet Ricaricato\", \"COM\": \"Tasso Commissione\", \"MSG\": \"Commento White Brand\", \"STATUS\": \"3\", \"EXTRA\": { \"IS3DS\": \"0\", \"CTRY\": \"FRA\", \"AUTH\": \"455622\" }, \"INT_MSG\": \"05-00-05 ERR_PSP_REFUSED\", \"MLABEL\": \"IBAN\", \"TYPE\": \"1\" } ] } }";
}
Here I use Google Gosn lib for conversion.
And need to import bellow classes for annotation
com.google.gson.annotations.Expose;
com.google.gson.annotations.SerializedName;
First parse the json data using json.simple and then set the values using setters
Object obj = parser.parse(new FileReader( "file.json" ));
JSONObject jsonObject = (JSONObject) obj;
JSONArray hpayObj= (JSONArray) jsonObject.get("HPAY");
//get the first element of array
JSONObject details= hpayObj.getJSONArray(0);
String id = (String)details.get("ID");
//set the value of the id field in the setter of class Trans
new Trans().setId(id);
new Trans().setDate((String)details.get("DATE"));
new Trans().setRec((String)details.get("REC"));
and so on..
//get the second array element
JSONObject intMsgObj= hpayObj.getJSONArray(1);
new Trans().setIntmsg((String)details.get("INT_MSG"));
//get the third array element
JSONObject mlabelObj= hpayObj.getJSONArray(2);
new Trans().setMlabel((String)details.get("MLABEL"));
JSONObject typeObj= hpayObj.getJSONArray(3);
new Trans().setType((String)details.get("TYPE"));
Now you can get the values using your getter methods.
I have JSON like this
{
"data":
[
{
"id": 1,
"Name": "Choc Cake",
"Image": "1.jpg",
"Category": "Meal",
"Method": "",
"Ingredients":
[
{
"name": "1 Cup Ice"
},
{
"name": "1 Bag Beans"
}
]
},
{
"id": 2,
"Name": "Ice Cake",
"Image": "dfdsfdsfsdfdfdsf.jpg",
"Category": "Meal",
"Method": "",
"Ingredients":
[
{
"name": "1 Cup Ice"
}
]
}
]
}
I am using JSON Object to de-Serialize the data
this is what i am trying to
JSONObject jsonObj = new JSONObject(jsonStr);
String first = jsonObj.getJSONObject("data").getString("name");
System.out.println(first);
But a Cant seem to get the name or anything
Not sure what i am doing wrong?
and then i am trying to display it into a listview but haven't got to that part yet
data is a JSON Array, not a JSONObject
try: jsonObj.getJSONArray("data").getJSONObject(0).getString("name")
also note the difference between getString and optString, if you don't want an exception on null use the later.
First parse your Json from below method,
private ArrayList<String> getStringFromJson(String jsonStr)
{
ArrayList<String> mNames = new ArrayList<String>();
JSONArray array = new JSONArray(jsonStr);
for (int i = 0; i < array.length(); i++) {
JSONObject row = array.getJSONObject(i);
mNames= row.getString("Name");
}
return mNames;
}
try {
JSONObject jsonObj = new JSONObject(jsonStr);
jsonObj.getJSONArray("data").getJSONObject(0).getString("name")
} catch (JSONException e) {
}
Data is a json array. Use getJsonObject for json objects.
Refer to this example to create a ListView and populate it's adapter with data from a json object.
Use GSON instead JSON. Hope it helps you.
GsonBuilder gsonBuilder = new GsonBuilder();
Gson gson = gsonBuilder.create();
List<Data> datas= new ArrayList<Data>();
datas= Arrays.asList(gson.fromJson(jsonString, Data[].class));
public class Ingredients {
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
private String name;
}
public class Data {
private int id;
private String Name;
private String Image;
private String Category;
private String Method;
public List<Ingredients> getIngredients() {
return Ingredients;
}
public void setIngredients(List<Ingredients> ingredients) {
Ingredients = ingredients;
}
private List<Ingredients> Ingredients = new ArrayList<Ingredients>();
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return Name;
}
public void setName(String name) {
Name = name;
}
public String getImage() {
return Image;
}
public void setImage(String image) {
Image = image;
}
public String getCategory() {
return Category;
}
public void setCategory(String category) {
Category = category;
}
public String getMethod() {
return Method;
}
public void setMethod(String method) {
Method = method;
}
}
I have a json object as like this:
[
{
"created_at": "2014-07-01 5:01:10",
"status": "in progress",
"device_id": "1234",
"order_details": [
{
"item_id": 1,
"quantity": 2
},
{
"item_id": 2,
"quantity": 3
}
]
}
]
And in java I have two classes order and order details as like this:
1) Order.java
package dto;
import java.util.ArrayList;
public class Order
{
int order_id;
String created_at;
String status;
String device_id;
ArrayList<Order_details> orderList= new ArrayList<Order_details>();
public int getOrder_id() {
return order_id;
}
public void setOrder_id(int order_id) {
this.order_id = order_id;
}
public String getCreated_at() {
return created_at;
}
public void setCreated_at(String created_at) {
this.created_at = created_at;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getDevice_id() {
return device_id;
}
public void setDevice_id(String device_id) {
this.device_id = device_id;
}
public ArrayList<Order_details> getOrderList() {
return orderList;
}
public void setOrderList(ArrayList<Order_details> orderList) {
this.orderList = orderList;
}
public void attachOrderDetails(ArrayList<Order_details> member) {
this.orderList = member;
}
}
2) Order_details.java
package dto;
public class Order_details
{
int item_id;
int quantity;
String item_name;
double price;
public int getItem_id()
{
return item_id;
}
public void setItem_id(int item_id)
{
this.item_id = item_id;
}
public int getQuantity()
{
return quantity;
}
public void setQuantity(int quantity)
{
this.quantity = quantity;
}
public String getItem_name()
{
return item_name;
}
public void setItem_name(String item_name)
{
this.item_name = item_name;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
}
now i want to convert above json object to the object of order class
To achieve this i have tried it:
Order order= new Order();
order= gs.fromJson(json,Order.class);
System.out.println("order"+order);
but it throws exception as follows:
com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was BEGIN_ARRAY at line 1 column 2
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapte rFactory.java:176)
at com.google.gson.Gson.fromJson(Gson.java:791)
at com.google.gson.Gson.fromJson(Gson.java:757)
at com.google.gson.Gson.fromJson(Gson.java:706)
at com.google.gson.Gson.fromJson(Gson.java:678)
Please, help me out to convert my json to my java object.
The first [ in your json says its holding an array or Order objects. So you need to make a list of orders rather than a single order class.
List<Order> order = new ArrayList<Order>();
order = gs.fromJson(json, order.getClass());
System.out.println("order" + order);
Or using type token as
List<Order> order = new ArrayList<Order>();
Type listType = new TypeToken<List<Order>>() {}.getType();
order = gs.fromJson(json, listType);
System.out.println("order" + order);
Alternatively to work with your code directly you need to modify your json to
{
"created_at": "2014-07-01 5:01:10",
"status": "in progress",
"device_id": "1234",
"order_details": [
{
"item_id": 1,
"quantity": 2
},
{
"item_id": 2,
"quantity": 3
}
]
}
When you are using GSON,then you should be more aware of case sensitive w.r.t key name and variable name.
either change variable name to
ArrayList<Order_details> order_details= new ArrayList<Order_details>(); instead of
ArrayList<Order_details> orderList= new ArrayList<Order_details>();
or
change json key name to orderList instead of order_details
Your JSON string can not cast directly to your class because your json contain array of the parameters of class Order and to convert it into class object you need list of Order class so that this array can be converted to list of Order.
For that you need to take List<Order> of Order class as shown below :
List<Order> orderList = new ArrayList<Order>();
Type listType = new TypeToken<List<Order>>(){}.getType();
orderList = json.fromJson(jsonStr, listType);
May this will help you.
I am using Spring Social FqlQuery to get data's from facebook. Here is the JSON response I am getting from facebook. My controller where i am getting Json output is here,
fql = "SELECT work FROM user WHERE uid = me()";
facebook.fqlOperations().query(fql, new FqlResultMapper<Object>() {
public Object mapObject(FqlResult result) {
List list = (List) result.getObject("work");
for (Object object : list) {
JsonHelper jsonHelper = new JsonHelper();
Gson gson = new GsonBuilder().setPrettyPrinting().create();
String jsonOutput = gson.toJson(object);
System.out.println(jsonOutput);
gson.fromJson(jsonOutput, JsonHelper.class);
}
System.out.println inside for loop Outputs multiple json as below.:
{
"employer": {
"id": 129843057436,
"name": "www.metroplots.com"
},
"location": {
"id": 102186159822587,
"name": "Chennai, Tamil Nadu"
},
"position": {
"id": 108480125843293,
"name": "Web Developer"
},
"start_date": "2012-10-01",
"end_date": "2013-05-31"
}
{
"employer": {
"id": 520808381292985,
"name": "Federation of Indian Blood Donor Organizations"
},
"start_date": "0000-00",
"end_date": "0000-00"
}
Here is my Helper Class:
import java.util.List;
public class JsonHelper {
class Employer{
private int id;
private String name;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
class Location{
private int id;
private String name;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
class Position{
private int id;
private String name;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
//Edited After here
private String start_Date;
private String end_Date;
private Employer employer;
private Location location;
private Position position;
public String getStart_Date() {
return start_Date;
}
public void setStart_Date(String start_Date) {
this.start_Date = start_Date;
}
public String getEnd_Date() {
return end_Date;
}
public void setEnd_Date(String end_Date) {
this.end_Date = end_Date;
}
public Employer getEmployer() {
return employer;
}
public void setEmployer(Employer employer) {
this.employer = employer;
}
public Location getLocation() {
return location;
}
public void setLocation(Location location) {
this.location = location;
}
public Position getPosition() {
return position;
}
public void setPosition(Position position) {
this.position = position;
}
}
When I try to convert the json objects to java object as done above I am getting this exception.
HTTP Status 500 - Request processing failed; nested exception is com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 6 column 16
Can any one help me where I am wrong. Please help me converting json to java objects. Hope my question is clear. Thanks in advance.
EDIT MADE TO CONTROLLER:
facebook.fqlOperations().query(fql, new FqlResultMapper<Object>() {
public Object mapObject(FqlResult result) {
List<JsonHelper> json = new ArrayList<JsonHelper>();
List list = (List) result.getObject("work");
for (Object object : list) {
Gson gson = new GsonBuilder().setPrettyPrinting().create();
String jsonOutput = gson.toJson(object);
System.out.println(jsonOutput);
JsonHelper jsonHelper = gson.fromJson(jsonOutput, JsonHelper.class);
json.add(jsonHelper);
System.out.println(jsonHelper.getStart_Date());
}
for (JsonHelper jsonHelper : json) {
System.out.println(jsonHelper.getStart_Date());
}
return list;
}
});
Since i am not having the actual api access, so i am trying it with static value in the example. Firstly in your JsonHelper class, replace all int by long , as the values mentioned in the json are of type long and String. Then try it like mentioned below:
String str = "{\n"
+ " \"employer\": {\n"
+ " \"id\": 129843057436,\n"
+ " \"name\": \"www.metroplots.com\"\n"
+ " },\n"
+ " \"location\": {\n"
+ " \"id\": 102186159822587,\n"
+ " \"name\": \"Chennai, Tamil Nadu\"\n"
+ " },\n"
+ " \"position\": {\n"
+ " \"id\": 108480125843293,\n"
+ " \"name\": \"Web Developer\"\n"
+ " },\n"
+ " \"start_date\": \"2012-10-01\",\n"
+ " \"end_date\": \"2013-05-31\"\n"
+ "}";
List<JsonHelper> json = new ArrayList<JsonHelper>();
Gson gson = new Gson();
JsonHelper users = gson.fromJson(str, JsonHelper.class);
json.add(users);
for (JsonHelper js_obj : json) {
System.out.println(js_obj.getEmployer().getId());
System.out.println(js_obj.getEmployer().getName());
}