json to java object with gson ( object nested with arraylist ) - json

I want to create a object Checklist with the following JSON. But I think the Arraylist categories isn't created. I do not have an exception the debug console enter into bucle when create the object : " Background partial concurrent mark sweep GC freed 165848(5MB) AllocSpace objects, 144(1852KB) LOS objects, 22% free, 55MB/71MB, paused 5.343ms total 67.660ms "
{"type_check":"CAB","description":"simple cabin","categories":[{"category_id":"3","description":"Confort"},{"category_id":"4","description":"Servicios"},{"category_id":"5","description":"Alimentación"},{"category_id":"6","description":"Personal"},{"category_id":"7","description":"Instalaciones"}]}
And the following classes:
Checklist.class
public class Checklist {
private String type_check;
private String description;
private ArrayList<Category> categories;}
Category.class
public class Category {
private int category_id;
private String description;
}
Creating the object:
Gson gson = new GsonBuilder().create();
Checklist check = gson.fromJson(checklist.toString(), Checklist.class);
I must specify the arraylist when I parse the json?? Thanks and have a nice day.

this is how the json would look like with following code
[
{
"type_check": "CAB_0",
"description": "simple cabin",
"categories": [
{
"category_id": 0,
"description": "Description_0"
},
{
"category_id": 1,
"description": "Description_1"
},
{
"category_id": 2,
"description": "Description_2"
},
{
"category_id": 3,
"description": "Description_3"
},
{
"category_id": 4,
"description": "Description_4"
},
{
"category_id": 5,
"description": "Description_5"
},
{
"category_id": 6,
"description": "Description_6"
}
]
},
{
"type_check": "CAB_1",
"description": "simple cabin",
"categories": [
{
"category_id": 0,
"description": "Description_0"
},
{
"category_id": 1,
"description": "Description_1"
},
{
"category_id": 2,
"description": "Description_2"
},
{
"category_id": 3,
"description": "Description_3"
},
{
"category_id": 4,
"description": "Description_4"
},
{
"category_id": 5,
"description": "Description_5"
},
{
"category_id": 6,
"description": "Description_6"
}
]
},
{
"type_check": "CAB_2",
"description": "simple cabin",
"categories": [
{
"category_id": 0,
"description": "Description_0"
},
{
"category_id": 1,
"description": "Description_1"
},
{
"category_id": 2,
"description": "Description_2"
},
{
"category_id": 3,
"description": "Description_3"
},
{
"category_id": 4,
"description": "Description_4"
},
{
"category_id": 5,
"description": "Description_5"
},
{
"category_id": 6,
"description": "Description_6"
}
]
},
{
"type_check": "CAB_3",
"description": "simple cabin",
"categories": [
{
"category_id": 0,
"description": "Description_0"
},
{
"category_id": 1,
"description": "Description_1"
},
{
"category_id": 2,
"description": "Description_2"
},
{
"category_id": 3,
"description": "Description_3"
},
{
"category_id": 4,
"description": "Description_4"
},
{
"category_id": 5,
"description": "Description_5"
},
{
"category_id": 6,
"description": "Description_6"
}
]
},
{
"type_check": "CAB_4",
"description": "simple cabin",
"categories": [
{
"category_id": 0,
"description": "Description_0"
},
{
"category_id": 1,
"description": "Description_1"
},
{
"category_id": 2,
"description": "Description_2"
},
{
"category_id": 3,
"description": "Description_3"
},
{
"category_id": 4,
"description": "Description_4"
},
{
"category_id": 5,
"description": "Description_5"
},
{
"category_id": 6,
"description": "Description_6"
}
]
},
{
"type_check": "CAB_5",
"description": "simple cabin",
"categories": [
{
"category_id": 0,
"description": "Description_0"
},
{
"category_id": 1,
"description": "Description_1"
},
{
"category_id": 2,
"description": "Description_2"
},
{
"category_id": 3,
"description": "Description_3"
},
{
"category_id": 4,
"description": "Description_4"
},
{
"category_id": 5,
"description": "Description_5"
},
{
"category_id": 6,
"description": "Description_6"
}
]
},
{
"type_check": "CAB_6",
"description": "simple cabin",
"categories": [
{
"category_id": 0,
"description": "Description_0"
},
{
"category_id": 1,
"description": "Description_1"
},
{
"category_id": 2,
"description": "Description_2"
},
{
"category_id": 3,
"description": "Description_3"
},
{
"category_id": 4,
"description": "Description_4"
},
{
"category_id": 5,
"description": "Description_5"
},
{
"category_id": 6,
"description": "Description_6"
}
]
}
]
Checklist.Java code is here
public class Checklist {
private String type_check;
private String description;
private ArrayList<Category> categories;
public String getType_check() {
return type_check;
}
public void setType_check(String type_check) {
this.type_check = type_check;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public ArrayList<Category> getCategories() {
return categories;
}
public void setCategories(ArrayList<Category> categories) {
this.categories = categories;
}
}
Category.java code is here
public class Category {
private int category_id;
private String description;
public int getCategory_id() {
return category_id;
}
public void setCategory_id(int category_id) {
this.category_id = category_id;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}
TestCode.Java code is here
import java.util.ArrayList;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
public class TestCode {
public static void main(String[] args) {
ArrayList<Checklist> list = new ArrayList<Checklist>();
list = createList();
String stringJson = (new Gson()).toJson(list);
System.out.println("##### JSON from a object #######");
System.out.println(stringJson);
System.out.println("###### Convert JSON to object ######");
ArrayList<Checklist> list2 = new ArrayList<Checklist>();
list2 = (new Gson()).fromJson(stringJson,
new TypeToken<ArrayList<Checklist>>() {
}.getType());
System.out.println("####### print out put ######");
for (int i = 0; i < list2.size(); i++) {
Checklist checklist = list2.get(i);
System.out.println(checklist.getType_check() + "");
System.out.println(checklist.getDescription() + "");
ArrayList<Category> categorys = checklist.getCategories();
for (int j = 0; j < categorys.size(); j++) {
Category category = categorys.get(j);
System.out.println(category.getCategory_id() + "");
System.out.println(category.getDescription() + "");
}
}
}
private static ArrayList<Checklist> createList() {
// TODO Auto-generated method stub
ArrayList<Checklist> list = new ArrayList<Checklist>();
for (int i = 0; i < 7; i++) {
Checklist checklist = new Checklist();
checklist.setType_check("CAB_" + i);
checklist.setDescription("simple cabin");
ArrayList<Category> categorys = new ArrayList<Category>();
for (int j = 0; j < 7; j++) {
Category category = new Category();
category.setCategory_id(j);
category.setDescription("Description_" + j);
categorys.add(category);
}
checklist.setCategories(categorys);
list.add(checklist);
}
return list;
}
}

Related

JsonBackReference not working as expected

I have the next two clases...
Class A
#Entity
#Table(name="ClassA")
public class ClassA
{
#Id
#GeneratedValue(strategy = IDENTITY)
#Column(name = "Id", unique = true, nullable = false)
private Long id;
#Column(name = "Name", nullable = false, length = 50)
private String name;
#JsonManagedReference
#OneToMany(mappedBy="classA")
private List<ClassB> classBList;
}
Class B
#Entity
#Table(name = "ClassB")
public class ClassB
{
#Id
#GeneratedValue(strategy = IDENTITY)
#Column(name = "Id", unique = true, nullable = false)
private Long id;
#Column(name = "Name", nullable = false, length = 50)
private String name;
#JsonBackReference
#ManyToOne
#JoinColumn(name = "ClassAId", nullable = false)
private ClassA classA;
}
When i do a get of all ClassA records from database using REST the result is working like charm:
GET http://localhost:8080/REST/ClassA
[
{
"id": 1,
"name": "VVVV I",
"classB": [
{
"id": 1,
"name": "SSSS I"
},
{
"id": 2,
"name": "QQQQ II",
}
]
},
{
"id": 2,
"name": "RRRR II",
"classB": []
},
{
"id": 3,
"name": "FFFFF III",
"classB": []
},
{
"id": 4,
"name": "QWERR",
"classB": [
{
"id": 3,
"name": "GGGG III",
},
{
"id": 4,
"name": "HHHH IV",
},
{
"id": 5,
"name": "JJJJ V",
}
]
},
{
"id": 5,
"name": "TRRR",
"classB": []
}
]
The problem is when i want to get the list of ClassB, the ClassA is not returning at all...
GET http://localhost:8080/REST/ClassB
[
{
"id": 1,
"name": "SSSS I"
},
{
"id": 2,
"name": "QQQQ II"
},
{
"id": 3,
"name": "GGGG III"
},
{
"id": 4,
"name": "HHHH IV"
},
{
"id": 5,
"name": "JJJJ V"
}
]
I need ClassA (without classB inside of it) be listed when getting list of ClassB
How can i achieve that?
Best regards

How to process sabre InstaFlight API JSON response

I connected to saber InstaFlight API and got a result in JSON. The output string is too long and I can get their values. But my way is taking lots of memory storage. I want a way that takes less memory storage and a dynamic way in VB.NET.
The code below is working fine with no error:
response2 = DirectCast(postReq.GetResponse(), HttpWebResponse)
reader2 = New StreamReader(response2.GetResponseStream())
postReq.ContentType = "application/json; charset=utf-8"
Dim ser1 As JObject = JObject.Parse(reader2.ReadToEnd())
I can get the values like this, with no error:
ElapseTime1 = ser1("PricedItineraries")(0)("AirItinerary")("OriginDestinationOptions")("OriginDestinationOption")(0)("ElapsedTime").Value(Of String)()
However, it gets to a point that you need hundreds of variables and this is not the right way.
An example of the output JSON:
{ "PricedItineraries": [ { "AirItinerary": { "OriginDestinationOptions": { "OriginDestinationOption": [ { "FlightSegment": [ { "DepartureAirport": { "LocationCode": "JFK" }, "ArrivalAirport": { "LocationCode": "LAS" }, "MarketingAirline": { "Code": "AS" }, "ArrivalTimeZone": { "GMTOffset": -7 }, "TPA_Extensions": { "eTicket": { "Ind": true } }, "StopQuantity": 0, "ElapsedTime": 344, "ResBookDesigCode": "R", "MarriageGrp": "O", "Equipment": { "AirEquipType": 320 }, "DepartureDateTime": "2017-07-07T09:30:00", "ArrivalDateTime": "2017-07-07T12:14:00", "FlightNumber": 1251, "OnTimePerformance": { "Percentage": 70 }, "OperatingAirline": { "CompanyShortName": "VIRGIN AMERICA", "FlightNumber": 251, "Code": "VX" }, "DepartureTimeZone": { "GMTOffset": -4 } }, { "DepartureAirport": { "LocationCode": "LAS" }, "ArrivalAirport": { "LocationCode": "LAX" }, "MarketingAirline": { "Code": "AS" }, "ArrivalTimeZone": { "GMTOffset": -7 }, "TPA_Extensions": { "eTicket": { "Ind": true } }, "StopQuantity": 0, "ElapsedTime": 85, "ResBookDesigCode": "R", "MarriageGrp": "O", "Equipment": { "AirEquipType": 320 }, "DepartureDateTime": "2017-07-07T14:45:00", "ArrivalDateTime": "2017-07-07T16:10:00", "FlightNumber": 1475, "OnTimePerformance": { "Percentage": 36 }, "OperatingAirline": { "CompanyShortName": "VIRGIN AMERICA", "FlightNumber": 475, "Code": "VX" }, "DepartureTimeZone": { "GMTOffset": -7 } } ], "ElapsedTime": 580 }, { "FlightSegment": [ { "DepartureAirport": { "LocationCode": "LAX" }, "ArrivalAirport": { "LocationCode": "LAS" }, "MarketingAirline": { "Code": "AS" }, "ArrivalTimeZone": { "GMTOffset": -7 }, "TPA_Extensions": { "eTicket": { "Ind": true } }, "StopQuantity": 0, "ElapsedTime": 71, "ResBookDesigCode": "R", "MarriageGrp": "O", "Equipment": { "AirEquipType": 320 }, "DepartureDateTime": "2017-07-08T17:00:00", "ArrivalDateTime": "2017-07-08T18:11:00", "FlightNumber": 1480, "OnTimePerformance": { "Percentage": 55 }, "OperatingAirline": { "CompanyShortName": "VIRGIN AMERICA", "FlightNumber": 480, "Code": "VX" }, "DepartureTimeZone": { "GMTOffset": -7 } }, { "DepartureAirport": { "LocationCode": "LAS" }, "ArrivalAirport": { "LocationCode": "JFK" }, "MarketingAirline": { "Code": "AS" }, "ArrivalTimeZone": { "GMTOffset": -4 }, "TPA_Extensions": { "eTicket": { "Ind": true } }, "StopQuantity": 0,
I think you need to create a model for this result. According to this JSON, you have to create a class model.
If you have this JSON:
{
"dailyDealId": "432",
"discountPercentage": "0",
"product": {
"productId": "10",
"brandId": "10",
"departmentId": "3",
"name": "Baby Girl Velour Tunic & Snowflake Legging Set",
"description": "The pretty set",
"url": "http://whatever.whatever.com/files/whatever.tif"
}
You need this model:
public class Product
{
public string productId { get; set; }
public string brandId { get; set; }
public string departmentId { get; set; }
public string name { get; set; }
public string description { get; set; }
public string url { get; set; }
}
public class Data
{
public string dailyDealId { get; set; }
public string discountPercentage { get; set; }
public Product product { get; set; }
}

Return json from two classes in model

I'm trying to return json with two classes in my model
public function both()
{
return $this->belongsToMany(Car::class)->and(Driver::class)->withPivot('type'); // this is wrong
}
the reason I'm trying to get this like that is because in my function
public function check()
{
$user = JWTAuth::parseToken()->authenticate();
$id = $user->id;
$result = User::with('both')->where('id', $id)->get();
return response()->json($result);
}
right now in my model I have this
public function both()
{
return $this->belongsToMany(Car::class)->withPivot('type');
}
public function driver()
{
return $this->belongsToMany(Driver::class)->withPivot('type');
}
But the function returns json that has a different structure when both ends.
My question is can I have the function return a json with the same structure?
like this
[
{
"id": 4,
"name": null,
"phone": "9000",
"size_of_house": null,
"created_at": "2016-12-04 13:55:52",
"updated_at": "2017-03-08 14:03:44",
"deleted_at": null,
"both": [
{
"id": 177,
"name": "NIS",
"created_at": "2016-12-27 10:28:29",
"updated_at": "2016-12-27 10:28:29",
"pic": "http://localhost:8000/images/1482833485.jpg",
"pivot": {
"user_id": 4,
"car_id": 177,
"type": "car"
}
},
"both": [
{
"name": "Abdulaziz Alomhsen",
"age": "30",
"created_at": "2017-02-28 09:36:15",
"updated_at": "2017-03-08 08:46:06",
"status": "جايه",
"pic": "http://localhost:8000/images/1488714520.jpg",
"id": 2,
"pivot": {
"user_id": 4,
"driver_id": 2,
"type": "driver"
}
},

json responce is Multiple Array How i can Parse it using Volley

How to Show "Category" , according to Category "Title", & "Price"
in RecyclerView One Row.
my Api url is https://www.paidup.io/api/v1/businesses/212/menu
This Url returns response like:
[{
"category": "Espresso & Coffee",
"items": [{
"title": "Vacuum Coffee",
"size": [{
"label": "medium",
"price": 125
}, {
"label": "large",
"price": 145
}]
}, {
"title": "Cafe Latte",
"size": [{
"label": "small",
"price": 115
}, {
"label": "medium",
"price": 135
}, {
"label": "large",
"price": 150
}]
}, {
"title": "Cafe Mocha",
"size": [{
"label": "small",
"price": 115
}, {
"label": "medium",
"price": 135
}, {
"label": "large",
"price": 150
}]
}, {
"title": "White Mocha",
"size": [{
"label": "small",
"price": 120
}, {
"label": "medium",
"price": 145
}, {
"label": "large",
"price": 155
}]
}, {
"title": "Caramel Macchiato",
"size": [{
"label": "small",
"price": 125
}, {
"label": "medium",
"price": 145
}, {
"label": "large",
"price": 165
}]
}, {
"title": "Coffee De Leche",
"size": [{
"label": "small",
"price": 130
}, {
"label": "medium",
"price": 145
}, {
"label": "large",
"price": 160
}]
}, {
"title": "Cafe-UK Coffee Lava",
"size": null,
"price": 145
}]
}, {
"category": "Frappe",
"items": [{
"title": "Coffee Base",
"size": [{
"label": "small",
"price": 140
}, {
"label": "medium",
"price": 155
}, {
"label": "large",
"price": 170
}]
}, {
"title": "Milk Base",
"size": [{
"label": "small",
"price": 130
}, {
"label": "medium",
"price": 145
}, {
"label": "large",
"price": 160
}]
}, {
"title": "Cream Soda Float w\/Ice-cream",
"size": null,
"price": 140
}]
}, {
"category": "Milk Tea & Juice",
"items": [{
"title": "Milk Tea",
"size": [{
"label": "small",
"price": 105
}, {
"label": "medium",
"price": 120
}]
}, {
"title": "Hot Tea",
"size": null,
"price": 120
}, {
"title": "Italian Soda",
"size": [{
"label": "small",
"price": 105
}, {
"label": "medium",
"price": 120
}, {
"label": "large",
"price": 140
}]
}, {
"title": "Juice",
"size": null,
"price": 105
}]
}, {
"category": "Food",
"items": [{
"title": "Ultimate Chili Con Fries",
"size": null,
"price": 290
}, {
"title": "Nachos",
"size": null,
"price": 290
}, {
"title": "Marble Potato Fondue",
"size": null,
"price": 120
}, {
"title":"Breakfast",
"size":null,
"price":220
}]}]
and my POJO Classes are Like:
package ph.paidup.models;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
/**
* Created by oxiloindia on 3/30/2016.
*/
public class Item {
#SerializedName("title")
#Expose
private String title;
#SerializedName("size")
#Expose
private Object size;
#SerializedName("price")
#Expose
private Integer price;
/**
*
* #return
* The title
*/
public String getTitle() {
return title;
}
/**
*
* #param title
* The title
*/
public void setTitle(String title) {
this.title = title;
}
/**
*
* #return
* The size
*/
public Object getSize() {
return size;
}
/**
*
* #param size
* The size
*/
public void setSize(Object size) {
this.size = size;
}
/**
*
* #return
* The price
*/
public Integer getPrice() {
return price;
}
/**
*
* #param price
* The price
*/
public void setPrice(Integer price) {
this.price = price;
}
}
and another class:
package ph.paidup.models;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.Generated;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
/**
* Created by oxiloindia on 3/30/2016.
*/
#Generated("org.jsonschema2pojo")
public class MenuRequest {
#SerializedName("category")
#Expose
private String category;
#SerializedName("items")
#Expose
private List<Item> items = new ArrayList<Item>();
/**
*
* #return
* The category
*/
public String getCategory() {
return category;
}
/**
*
* #param category
* The category
*/
public void setCategory(String category) {
this.category = category;
}
/**
*
* #return
* The items
*/
public List<Item> getItems() {
return items;
}
/**
*
* #param items
* The items
*/
public void setItems(List<Item> items) {
this.items = items;
}
}
Now i want to parse this in my Activity to Get
According to
"category" , needs its
"title" and
"price" in recyclerview
i am Trying to do it Like this way:
public void getInVoice() {
showProgress(true);
String URL="https://www.paidup.io/api/v1/businesses/212/menu";
JsonArrayRequest req = new JsonArrayRequest(Request.Method.GET,URL,null, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
showProgress(false);
VolleyLog.v("Response:%n %s", response);
Gson gson = new GsonBuilder().create();
for (int i = 0; i < response.length(); i++) {
try {
JSONObject jsonObject = new JSONObject();
String desc = jsonObject.getString("category");
JsonParser jsonParser = new JsonParser();
groupItem.items = (List<Item>) jsonParser.parse(String.valueOf(response));
// Create a new adapter with data items
mExpandableAdapter = new BakeryMenuExpandableAdapter(getActivity(), setUpList(groupItem.items)) {
#Override
public void onItemClick(int position, View v) {
}
};
// Attach this activity to the Adapter as the ExpandCollapseListener
mExpandableAdapter.setExpandCollapseListener(new ExpandableRecyclerAdapter.ExpandCollapseListener() {
#Override
public void onListItemExpanded(int position) {
Log.e("CHEEE", "" + position);
}
#Override
public void onListItemCollapsed(int position) {
}
});
// Set the RecyclerView's adapter to the ExpandableAdapter we just created
recyclerView.setAdapter(mExpandableAdapter);
// Set the layout manager to a LinearLayout manager for vertical list
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
} catch (Exception e) {
Log.e("My App", "Could not parse malformed JSON: \"" + response + "\"");
e.printStackTrace();
}
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Activity activity = getActivity();
if (activity != null && isAdded())
showProgress(false);
Toast.makeText(getActivity(), "Something went wrong. please try it again", Toast.LENGTH_SHORT).show();
}
});
// add the request object to the queue to be executed
addToRequestQueue(req, TAG);
}
I tried all Requests to Parse it but couldn't get success.
What should i need to do in Try block to get List of Items for recyclerview
thanks in advance....plz solve it
You have errors in your response callback.
1) You use JsonRequest of volley but you actually want to parse it into a POJO with Gson.
2) you get array of menurequest objects but it seems you handle then as just one MenuRequest
so you don't really need those:
JSONObject jsonObject = new JSONObject();
String desc = jsonObject.getString("category");
JsonParser jsonParser = new JsonParser();
groupItem.items = (List<Item>) jsonParser.parse(String.valueOf(response));
These actually throws different exceptions.
instead you can do:
MenuRequest[] items = gson.fromJson(response.toString(), MenuRequest[].class);
so in items you will endup with an Array of MenuRequest objects
then you can do whatever you need for example:
for(MenuRequest item:items) {
Log.d("test", "item: " +item);
}

Export / Import ECMASCRIPT 6 Class with JSON

This is all using ecmascript 6; Say I have a class
class Hero {
constructor(id,name){
this.id=id;
this.name=name;
}
}
And I want to have create an array of object of that type of class:
var HEROES = [
{ "id": 11, "name": "Mr. Nice" },
{ "id": 12, "name": "Narco" },
{ "id": 13, "name": "Bombasto" },
{ "id": 14, "name": "Celeritas" },
{ "id": 15, "name": "Magneta" },
{ "id": 16, "name": "RubberMan" },
{ "id": 17, "name": "Dynama" },
{ "id": 18, "name": "Dr IQ" },
{ "id": 19, "name": "Magma" },
{ "id": 20, "name": "Tornado" }
];
Is there a way to do this besides manually parsing the array and then doing New Hero() for each element? It would be nice to be able to do something like HEROES[] = hero.jsonExport() and then later var = hero.jsonImport(HEROES[i]). I've been looking around but without using Typescript this doesn't seem particularly easy. Am I missing something easy?
Thanks!
-Eric
Seems strange to want to import from a specific array instance - especially given that the order could change. It would probably be better to export a factory function which creates a new Hero based off the criteria:
class Hero {
constructor(id,name){
this.id=id;
this.name=name;
}
}
const HEROES = [
{ "id": 11, "name": "Mr. Nice" },
{ "id": 12, "name": "Narco" },
{ "id": 13, "name": "Bombasto" },
{ "id": 14, "name": "Celeritas" },
{ "id": 15, "name": "Magneta" },
{ "id": 16, "name": "RubberMan" },
{ "id": 17, "name": "Dynama" },
{ "id": 18, "name": "Dr IQ" },
{ "id": 19, "name": "Magma" },
{ "id": 20, "name": "Tornado" }
];
export default function createHero(index) {
const hero = HEROES[index];
return new Hero(hero.id,hero.name);
}
And the caller:
import createHero from "./hero";
const hero1 = createHero(1);