All json objects get updated on text change? - java

This is my log for the 1st text change
[{
"custInfo": "Anup 8600931386",
"rate": "24032",
"weight": "21.00000",
"makingAmt": "232",
"description": "GENTS ANGTHI 22k NO STONE",
"sum_total": "50954.4",
"vat": "",
"itemTotal": "50954.4",
"barcode": "BQSP78BB",
"net_rate": "24264.0",
"date": "09-12-2015",
"invoiceNo": "1",
"bill_type": "Estimate"
}]
Now when I add one more entry the previous item also gets updated.This is the log after the 2nd entry.
[{
"custInfo": "Anup 8600931386",
"rate": "24052",
"weight": "12.00000",
"makingAmt": "228",
"description": "LADIES TOP 22K NO STONE",
"sum_total": "29136.0",
"vat": "",
"itemTotal": "29136.0",
"barcode": "BQSP82BB",
"net_rate": "24280.0",
"date": "09-12-2015",
"invoiceNo": "1",
"bill_type": "Estimate"
}, {
"custInfo": "Anup 8600931386",
"rate": "24052",
"weight": "12.00000",
"makingAmt": "228",
"description": "LADIES TOP 22K NO STONE",
"sum_total": "29136.0",
"vat": "",
"itemTotal": "29136.0",
"barcode": "BQSP82BB",
"net_rate": "24280.0",
"date": "09-12-2015",
"invoiceNo": "1",
"bill_type": "Estimate"
}]
This is my text watcher implementation and the code that updates the values is inside after text changed().
private TextWatcher mkAmountTextWatcher = new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
#Override
public void afterTextChanged(Editable s) {
String mkAmt = makingAmount.getText().toString();
mk = Double.parseDouble(mkAmt);
calculateAndShow(wt, rt, mk);
int mid = (int) newRow.getTag()-1;
if ((mid<0) || (mid>itemSelectedJson.length())){
return;
}
try{
itemSelectedJson.getJSONObject(mid).put("makingAmt",mkAmt);
Log.d("MAKING_TW", itemSelectedJson.toString());
} catch (JSONException e) {
e.printStackTrace();
}
}
};
This is the code for creating the json array.
private void createJsonArray() {
billType = (invEstSwitch.isChecked() ? textViewEstimate : textViewInvoice)
.getText().toString();
String invNumber = textViewInvNo.getText().toString();
String bcode = barCode.getText().toString();
String description = itemDesc.getText().toString();
String wt = weightLine.getText().toString();
String rateAmt = rateAmount.getText().toString();
String making = makingAmount.getText().toString();
String netr = netRate.getText().toString();
String iTotal = itemtotal.getText().toString();
String vatAmt = textViewVat.getText().toString();
String sumAmt = textViewSum.getText().toString();
String crtDate = textViewCurrentDate.getText().toString();
try {
jsonObject.put("custInfo", custSelected.toString());
jsonObject.put("invoiceNo", invNumber);
jsonObject.put("barcode", bcode);
jsonObject.put("description", description);
jsonObject.put("weight", wt);
jsonObject.put("rate", rateAmt);
jsonObject.put("makingAmt", making);
jsonObject.put("net_rate", netr);
jsonObject.put("itemTotal", iTotal);
jsonObject.put("vat", vatAmt);
jsonObject.put("sum_total", sumAmt);
jsonObject.put("bill_type", billType);
jsonObject.put("date", crtDate);
} catch (JSONException e) {
e.printStackTrace();
}
try {
itemSelectedJson.put(index, jsonObject);
index++;
} catch (JSONException e) {
e.printStackTrace();
}
}

In this Method createJsonArray() you are not using same JSONObject every time. That's why you are getting same content again and again.
Just try to initialize jsonObject in createJsonArray() method first, then I guess, it will work.

Related

How can I get inside info object using volley in android java

this is the json data and i want to display the info object using volley in android java i hope you can answer this question thank you
"data": {
"type": "customer",
"name": "Sasmple name",
"phone": "1234567",
"email": "sample#gmail.com",
"email_verified_at": null,
"created_at": "2021-05-04T08:24:49.000000Z",
"updated_at": "2021-05-04T08:24:49.000000Z",
"info": {
"id": 63,
"user_id": 381,
"fname": "Sample",
"mname": null,
"lname": "Name",
"gender": null,
"image": null,
"birthdate": null,
"address": "Sample, Sample City (capital), Sample",
"address_code": "{\"region\":\"07\",\"province\":\"0722\",\"citymun\":\"072217\",\"barangay\":\"072217027\"}",
"bank_number": "17171717171717171717",
"bank_name": "Sample bank",
"created_at": "2021-05-04T08:24:49.000000Z",
"updated_at": "2021-05-04T08:24:49.000000Z"
}
}
and this is my code that i used
JSONObject json= null;
try {
json = new JSONObject("info");
for(int i=0; i<json.length(); i++){
JSONObject item = json.getJSONObject(String.valueOf(json));
String province_id = item.getString("id");
String province_code = item.getString("fname");
String province_desc = item.getString("lname");
String province_regcode = item.getString("address");
String province_citycode = item.getString("address_code");
}
} catch (JSONException e) {
e.printStackTrace();
}
Please read more about JSON Object and Json Array here
To answer for your question
try {
JSONObject jsonData = new JSONObject(httpStringResponse);
JSONObject infoItem = json.getJSONObject("info");
String province_id = infoItem.getString("id");
String province_code = infoItem.getString("fname");
String province_desc = infoItem.getString("lname");
String province_regcode = infoItem.getString("address");
String province_citycode = infoItem.getString("address_code");
} catch (JSONException e) {
e.printStackTrace();
}

Nested JSON Array in Java

I need to create a json response like the one below. I tried with some code but couldn't able to get what i need. Need help in java code to create nested array to group the food items according to the categories along with the category details like in below json
{
"menu": {
"items": [{
"id": 1,
"code": "hot1_sub1_mnu",
"name": "Mutton",
"status": "1",
"sub_items": [{
"id": "01",
"name": "Mutton Pepper Fry",
"price": "100"
}, {
"id": "02",
"name": "Mutton Curry",
"price": "100"
}]
},
{
"id": "2",
"code": "hot1_sub2_mnu",
"name": "Sea Food",
"status": "1",
"sub_items": [{
"id": "01",
"name": "Fish Fry",
"price": "150"
}]
},
{
"id": "3",
"code": "hot1_sub3_mnu",
"name": "Noodles",
"status": "1",
"sub_items": [{
"id": "01",
"name": "Chicken Noodles",
"price": "70"
}, {
"id": "02",
"name": "Egg Noodles",
"price": "60"
}]
}
]
}
}
What i tried so far will give response in one single array.
#Path("/items")
public class HotelsMenu {
#GET
#Path("/getitems")
#Produces(MediaType.APPLICATION_JSON)
public String doLogin(#QueryParam("hotelcode") String hotelcode) {
JSONObject response = new JSONObject();
JSONArray hotelDetails = checkCredentials(hotelcode);
try {
response.put("hotels", hotelDetails);
response.put("status", (hotelDetails == new JSONArray()) ? "false" : "true");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return response.toString();
}
private JSONArray checkCredentials(String hotelcode) {
System.out.println("Inside checkCredentials");
JSONArray result = new JSONArray();
try {
result = DBConnection.checkItems(hotelcode);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return result;
}
public static JSONArray checkItems(String hotelcode) throws Exception {
int id;
String code = hotelcode + "_mnu";
String name = null;
String name1 = null;
String status;
String price;
Connection dbConn = null;
Connection dbConn1 = null;
JSONArray hotels = new JSONArray();
JSONArray menu = new JSONArray();
try {
try {
dbConn = DBConnection.createConnection();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Statement stmt = dbConn.createStatement();
String query = "SELECT * FROM " + code + " where Status='1'";
System.out.println(query);
ResultSet rs1 = stmt.executeQuery(query);
System.out.println("hai");
while (rs1.next()) {
JSONObject hotel = new JSONObject();
id = rs1.getInt("Id");
hotel.put("id", id);
code = rs1.getString("Code");
System.out.println(code);
hotel.put("code", code);
name = rs1.getString("Name");
hotel.put("name", name);
status = rs1.getString("Status");
hotel.put("status", status);
hotels.put(hotel);
System.out.println("Hotel1:" + hotels);
try {
dbConn1 = DBConnection.createConnection();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Statement stmt1 = dbConn1.createStatement();
String query1 = "SELECT * FROM " + code + " where Status='1' ";
System.out.println(query1);
ResultSet rs2 = stmt1.executeQuery(query1);
while (rs2.next()) {
JSONArray hotel1 = new JSONArray();
JSONObject hotelmenu = new JSONObject();
id = rs2.getInt("Id");
hotelmenu.put("id", id);
name1 = rs2.getString("Name");
hotelmenu.put("name", name1);
price = rs2.getString("Price");
hotelmenu.put("price", price);
hotel1.put(hotelmenu);
hotels.put(hotel1);
System.out.println(hotels);
}
}
} catch (SQLException sqle) {
throw sqle;
} catch (Exception e) {
// TODO Auto-generated catch block
if (dbConn != null) {
dbConn.close();
}
throw e;
} finally {
if (dbConn != null) {
dbConn.close();
}
}
return hotels;
}
}
As previous answers suggests, you should re-design your model. I just did a quick restructuring of it. Check if this serves your purpose -
{
"menu": {
"items": [{
"id": 1,
"code": "hot1_sub1_mnu",
"name": "Mutton",
"status": "1",
"sub_items": [{
"id": "01",
"name": "Mutton Pepper Fry",
"price": "100"
}, {
"id": "02",
"name": "Mutton Curry",
"price": "100"
}]
},
{
"id": "2",
"code": "hot1_sub2_mnu",
"name": "Sea Food",
"status": "1",
"sub_items": [{
"id": "01",
"name": "Fish Fry",
"price": "150"
}]
},
{
"id": "3",
"code": "hot1_sub3_mnu",
"name": "Noodles",
"status": "1",
"sub_items": [{
"id": "01",
"name": "Chicken Noodles",
"price": "70"
}, {
"id": "02",
"name": "Egg Noodles",
"price": "60"
}]
}
]
}}
If the structure is OK, let know if you want help with the Java code to generate the above Json.
Also maybe go through the following libraries -
Jackson tutorial and Gson tutorial
//import java.util.ArrayList;
//import org.bson.Document;
Document root = new Document();
Document rootMenu = new Document();
ArrayList rootMenuItems = new ArrayList();
Document rootMenuItems0 = new Document();
ArrayList rootMenuItems0Sub_items = new ArrayList();
Document rootMenuItems0Sub_items0 = new Document();
Document rootMenuItems0Sub_items1 = new Document();
Document rootMenuItems1 = new Document();
ArrayList rootMenuItems1Sub_items = new ArrayList();
Document rootMenuItems1Sub_items0 = new Document();
Document rootMenuItems2 = new Document();
ArrayList rootMenuItems2Sub_items = new ArrayList();
Document rootMenuItems2Sub_items0 = new Document();
Document rootMenuItems2Sub_items1 = new Document();
rootMenuItems0.append("id", 1);
rootMenuItems0.append("code", "hot1_sub1_mnu");
rootMenuItems0.append("name", "Mutton");
rootMenuItems0.append("status", "1");
rootMenuItems0Sub_items0.append("id", "01");
rootMenuItems0Sub_items0.append("name", "Mutton Pepper Fry");
rootMenuItems0Sub_items0.append("price", "100");
rootMenuItems0Sub_items1.append("id", "02");
rootMenuItems0Sub_items1.append("name", "Mutton Curry");
rootMenuItems0Sub_items1.append("price", "100");
rootMenuItems1.append("id", "2");
rootMenuItems1.append("code", "hot1_sub2_mnu");
rootMenuItems1.append("name", "Sea Food");
rootMenuItems1.append("status", "1");
rootMenuItems1Sub_items0.append("id", "01");
rootMenuItems1Sub_items0.append("name", "Fish Fry");
rootMenuItems1Sub_items0.append("price", "150");
rootMenuItems2.append("id", "3");
rootMenuItems2.append("code", "hot1_sub3_mnu");
rootMenuItems2.append("name", "Noodles");
rootMenuItems2.append("status", "1");
rootMenuItems2Sub_items0.append("id", "01");
rootMenuItems2Sub_items0.append("name", "Chicken Noodles");
rootMenuItems2Sub_items0.append("price", "70");
rootMenuItems2Sub_items1.append("id", "02");
rootMenuItems2Sub_items1.append("name", "Egg Noodles");
rootMenuItems2Sub_items1.append("price", "60");
if (!rootMenuItems.isEmpty()) {
rootMenu.append("items", rootMenuItems);
}
if (!rootMenuItems0Sub_items.isEmpty()) {
rootMenuItems0.append("sub_items", rootMenuItems0Sub_items);
}
if (!rootMenuItems0Sub_items0.isEmpty()) {
rootMenuItems0Sub_items.add(rootMenuItems0Sub_items0);
}
if (!rootMenuItems0Sub_items.isEmpty()) {
rootMenuItems0.append("sub_items", rootMenuItems0Sub_items);
}
if (!rootMenuItems0Sub_items1.isEmpty()) {
rootMenuItems0Sub_items.add(rootMenuItems0Sub_items1);
}
if (!rootMenuItems0Sub_items.isEmpty()) {
rootMenuItems0.append("sub_items", rootMenuItems0Sub_items);
}
if (!rootMenuItems0.isEmpty()) {
rootMenuItems.add(rootMenuItems0);
}
if (!rootMenuItems.isEmpty()) {
rootMenu.append("items", rootMenuItems);
}
if (!rootMenuItems1Sub_items.isEmpty()) {
rootMenuItems1.append("sub_items", rootMenuItems1Sub_items);
}
if (!rootMenuItems1Sub_items0.isEmpty()) {
rootMenuItems1Sub_items.add(rootMenuItems1Sub_items0);
}
if (!rootMenuItems1Sub_items.isEmpty()) {
rootMenuItems1.append("sub_items", rootMenuItems1Sub_items);
}
if (!rootMenuItems1.isEmpty()) {
rootMenuItems.add(rootMenuItems1);
}
if (!rootMenuItems.isEmpty()) {
rootMenu.append("items", rootMenuItems);
}
if (!rootMenuItems2Sub_items.isEmpty()) {
rootMenuItems2.append("sub_items", rootMenuItems2Sub_items);
}
if (!rootMenuItems2Sub_items0.isEmpty()) {
rootMenuItems2Sub_items.add(rootMenuItems2Sub_items0);
}
if (!rootMenuItems2Sub_items.isEmpty()) {
rootMenuItems2.append("sub_items", rootMenuItems2Sub_items);
}
if (!rootMenuItems2Sub_items1.isEmpty()) {
rootMenuItems2Sub_items.add(rootMenuItems2Sub_items1);
}
if (!rootMenuItems2Sub_items.isEmpty()) {
rootMenuItems2.append("sub_items", rootMenuItems2Sub_items);
}
if (!rootMenuItems2.isEmpty()) {
rootMenuItems.add(rootMenuItems2);
}
if (!rootMenuItems.isEmpty()) {
rootMenu.append("items", rootMenuItems);
}
if (!rootMenu.isEmpty()) {
root.append("menu", rootMenu);
}
System.out.println(root.toJson());

Custom deserializer or different class design Retrofit

Retrofit makes things so easy for a noob like me. However, the API response structure that I'm requesting for my current project doesn't follow the same format as I have used before. I am unsure of whether I need to rewrite my POJO or make a custom deserializer in GSON. I cannot change the JSON structure and a custom deserializer seems daunting to me.
Here is the JSON:
{
"Green Shirt": [
{
"id": "740",
"name": “Nice Green Shirt",
"quantity": "0",
"make": "",
"model": "",
"price": “15.00",
"size": "XXS",
"sku": null,
"image": "https:\/\/google.com\/green_shirt.jpg",
"new_record": false,
"category_name": "",
"bar_code": "",
},
{
"id": "743",
"name": "Green Shirt",
"quantity": “68",
"make": "",
"model": "",
"price": “20.00",
"size": "XS",
"sku": null,
"image": "https:\/\/google.com\/green_shirt.jpg",
"new_record": false,
"category_name": "",
"bar_code": "",
}
],
"Dark Blue Jeans": [
{
"id": "1588",
"name": "Dark Blue Jeans",
"quantity": "0",
"make": "",
"model": "",
"price": "0.00",
"size": “S",
"sku": null,
"image": "https:\/\/google.com\/dark_blue_jeans.jpg",
"new_record": false,
"category_name": "",
"bar_code": "",
"category": null
},
{
"id": "1559",
"name": "Dark Blue Jeans",
"quantity": "4",
"make": "",
"model": "",
"price": "0.00",
"size": “XL",
"sku": null,
"image": "https:\/\/google.com\/dark_blue_jeans.jpg",
"new_record": false,
"category_name": "",
"bar_code": "",
"category": null
}
],
"White Belt": [
{
"id": "1536",
"name": "White Belt",
"quantity": "37",
"make": "",
"model": "",
"price": "0.00",
"size": "One Size",
"sku": null,
"image": "https:\/\/google.com\/white_belt.jpg",
"new_record": false,
"category_name": "",
"bar_code": "",
"category": null
}
]
}
Here is the POJO:
public class Product
{
private String model;
private String bar_code;
private String image;
private null sku;
private String new_record;
private String size;
private String id;
private null category;
private String price;
private String category_name;
private String name;
private String quantity;
private String make;
public String getModel ()
{
return model;
}
public void setModel (String model)
{
this.model = model;
}
public String getBar_code ()
{
return bar_code;
}
public void setBar_code (String bar_code)
{
this.bar_code = bar_code;
}
public String getImage ()
{
return image;
}
public void setImage (String image)
{
this.image = image;
}
public null getSku ()
{
return sku;
}
public void setSku (null sku)
{
this.sku = sku;
}
public String getNew_record ()
{
return new_record;
}
public void setNew_record (String new_record)
{
this.new_record = new_record;
}
public String getSize ()
{
return size;
}
public void setSize (String size)
{
this.size = size;
}
public String getId ()
{
return id;
}
public void setId (String id)
{
this.id = id;
}
public null getCategory ()
{
return category;
}
public void setCategory (null category)
{
this.category = category;
}
public String getPrice ()
{
return price;
}
public void setPrice (String price)
{
this.price = price;
}
public String getCategory_name ()
{
return category_name;
}
public void setCategory_name (String category_name)
{
this.category_name = category_name;
}
public String getName ()
{
return name;
}
public void setName (String name)
{
this.name = name;
}
public String getQuantity ()
{
return quantity;
}
public void setQuantity (String quantity)
{
this.quantity = quantity;
}
public String getMake ()
{
return make;
}
public void setMake (String make)
{
this.make = make;
}
#Override
public String toString()
{
return "ClassPojo [model = "+model+", bar_code = "+bar_code+", image = "+image+", sku = "+sku+", new_record = "+new_record+", size = "+size+", id = "+id+", category = "+category+", price = "+price+", category_name = "+category_name+", name = "+name+", quantity = "+quantity+", make = "+make+"]";
}
}
Here is the request and Retrofit interface:
public static void requestData(String username,String password) {
RestAdapter.Builder builder = new RestAdapter.Builder()
.setClient(new OkClient(new OkHttpClient()))
.setEndpoint(ENDPOINT);
if (username != null && password != null) {
// concatenate username and password with colon for authentication
final String credentials = username + ":" + password;
builder.setRequestInterceptor(new RequestInterceptor() {
#Override
public void intercept(RequestFacade request) {
// create Base64 encodet string
String string = "Basic " + Base64.encodeToString(credentials.getBytes(), Base64.NO_WRAP);
request.addHeader("Accept", "application/json");
request.addHeader("Authorization", string);
}
});
}
RestAdapter adapter = builder.build();
ProductAPI api = adapter.create(ProductAPI.class);
api.getInventory(new Callback<List<Product>>() {
#Override
public void success(List<Product> products, Response response) {
Log.d(TAG, response.getUrl());
Log.d(TAG, response.getReason());
mInventory = product;
}
#Override
public void failure(RetrofitError error) {
Log.d(TAG,error.getMessage());
}
});
}
public interface ProductAPI {
#GET("/v2/get-inventory")
public void getInventory(Callback<List<Product>> response);
}
This is the error I get because the JSON starts with '{' instead of '['
com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 2 path $
Your JSON is invalid, try formatting it properly first before doing anything else.
Properly formatted:
{
"Green Shirt": [
{
"id": "740",
"name": "Nice Green Shirt",
"quantity": "0",
"make": "",
"model": "",
"price": "15.00",
"size": "XXS",
"sku": null,
"image": "https:\\/\\/google.com\\/green_shirt.jpg",
"new_record": false,
"category_name": "",
"bar_code": ""
},
{
"id": "743",
"name": "Green Shirt",
"quantity": "68",
"make": "",
"model": "",
"price": "20.00",
"size": "XS",
"sku": null,
"image": "https:\\/\\/google.com\\/green_shirt.jpg",
"new_record": false,
"category_name": "",
"bar_code": ""
}
],
"Dark Blue Jeans": [
{
"id": "1588",
"name": "Dark Blue Jeans",
"quantity": "0",
"make": "",
"model": "",
"price": "0.00",
"size": "S",
"sku": null,
"image": "https:\\/\\/google.com\\/dark_blue_jeans.jpg",
"new_record": false,
"category_name": "",
"bar_code": "",
"category": null
},
{
"id": "1559",
"name": "Dark Blue Jeans",
"quantity": "4",
"make": "",
"model": "",
"price": "0.00",
"size": "XL",
"sku": null,
"image": "https:\\/\\/google.com\\/dark_blue_jeans.jpg",
"new_record": false,
"category_name": "",
"bar_code": "",
"category": null
}
],
"White Belt": [
{
"id": "1536",
"name": "White Belt",
"quantity": "37",
"make": "",
"model": "",
"price": "0.00",
"size": "One Size",
"sku": null,
"image": "https:\\/\\/google.com\\/white_belt.jpg",
"new_record": false,
"category_name": "",
"bar_code": "",
"category": null
}
]
}
Some of the errors it had:
Error:Strings should be wrapped in double quotes.[Code 17, Structure 12]
Error:Strings should be wrapped in double quotes.[Code 17, Structure 28]
Error:Invalid comma, expecting }.[Code 141, Structure 53]
Error:Expecting string, not }.[Code 8, Structure 54]
Error:Strings should be wrapped in double quotes.[Code 17, Structure 67]
Error:Strings should be wrapped in double quotes.[Code 17, Structure 79]
Error:Invalid comma, expecting }.[Code 141, Structure 104]
Error:Expecting string, not }.[Code 8, Structure 105]
Error:Strings should be wrapped in double quotes.[Code 17, Structure 138]
Error:Strings should be wrapped in double quotes.[Code 17, Structure 192]
The problem seems exactly what it says. The response is an object that has an array and not an array directly:
{ [{},{},{}] }
If the response was:
[{},{},{}]
It would work, but as you cannot change the response format you should change your java. Instead of expecting a List of Products you should have an object that has a List of Products inside. That is how retrofit will map it.
Edit:
The response is actually as follows:
{[],[],[]}
Is not a list, is an object composed with three Lists of Objects Product
The mapping to an object will have to be:
public class Wrapper
{
List<Product> WhiteBelt;
List<Product> DarkBlueJeans;
List<Product> GreenShirt;
}
Something like that would be your structure. I dont believe is right, because you usally want a list and not an object with three lists inside "hardcoded".
Let me know if it helps
Edited:
So you need somthing like this:
{
"products":
[{ "name" : "Green Shirt"
"items":
[{"id": "740",
"name": “Nice Green Shirt",
"quantity": "0",
"make": "",
"model": "",
"price": “15.00",
"size": "XXS",
"sku": null,
"image": "https:\/\/google.com\/green_shirt.jpg",
"new_record": false,
"category_name": "",
"bar_code": ""
}]
}]
}
That would be a structure that accepts a list of Products and inside each prodcut you have the list of items (the one you already have).
In Java:
public class ProductList
{
List <ProductList> productList;
}
public class ProductList
{
String name;
List<Product> items;
}
Using your original Product class
I told Retrofit (GSON?) to look for a Map<String,List<Product>> instead of just a List<Product> and it figured it out, how convenient.
:
api.getInventory(new Callback<Map<String,List<Product>>>() {
#Override
public void success(Map<String,List<Product>> products, Response response) {
mInventory = products;
}
#Override
public void failure(RetrofitError error) {
Log.d(TAG,error.getMessage());
}
});
public interface ProductAPI {
#GET("/v2/get-inventory")
public void getInventory(Callback<Map<String,List<Product>>> response);
}

How to replace all words so that it is inside double quote?

I have a below json string
{
"query": {
"filtered": {
"filter": {
"bool": {
"must": [{
"terms": {
"task_id": ["000JAGUAR8M,000JAGUAR94,000JAG0009I,000JQQ0009O,000JAGUAR6Y,000JAGUAR7H,000JAGUAR7I,000JAKAAL7J,000BAKAAL7K,000JAGUAR7L"]
}
}]
}
}
}
},
"size": 0,
"aggs": {
"task_ids": {
"terms": {
"field": "task_id",
"size": 0
}
}
}
}
I need to replace only task_id part inside terms so that each task is inside a double quote.
{
"query": {
"filtered": {
"filter": {
"bool": {
"must": [{
"terms": {
"task_id": ["000JAGUAR8M","000JAGUAR94","000JAG0009I","000JQQ0009O","000JAGUAR6Y","000JAGUAR7H","000JAGUAR7I","000JAKAAL7J","000BAKAAL7K","000JAGUAR7L"]
}
}]
}
}
}
},
"size": 0,
"aggs": {
"task_ids": {
"terms": {
"field": "task_id",
"size": 0
}
}
}
}
I am able to read the task_ids using below code, but how can I write back the changed value (requiredTasksIdValues) in the json object?
String str = "{\"query\":{\"filtered\":{\"filter\":{\"bool\":{\"must\":[{\"terms\":{\"task_id\":[\"000JAGUAR8M,000JAGUAR94,000JAG0009I,000JQQ0009O,000JAGUAR6Y,000JAGUAR7H,000JAGUAR7I,000JAKAAL7J,000BAKAAL7K,000JAGUAR7L\"]}}]}}}},\"size\":0,\"aggs\":{\"task_ids\":{\"terms\":{\"field\":\"task_id\",\"size\":0}}}}";
ObjectMapper mapper = new ObjectMapper();
try {
JsonNode taskIdsjsonNode = mapper.readTree(str);
JsonNode jn = taskIdsjsonNode.get("query").get("filtered").get("filter").get("bool").get("must").get(0).get("terms").get("task_id");
StringBuffer temp = new StringBuffer(jn.toString().substring(2));
temp = new StringBuffer(temp.substring(0, temp.length() - 2));
String[] temp_task_ids = temp.toString().split(",");
StringBuffer requiredTasksIdValues = new StringBuffer();
for (String taskid: temp_task_ids) {
requiredTasksIdValues.append("\""+taskid+"\",");
}
requiredTasksIdValues = new StringBuffer(requiredTasksIdValues.substring(0, requiredTasksIdValues.length() - 1));
System.out.println(requiredTasksIdValues);
} catch (JsonProcessingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(str);
String original = "000JAGUAR8M,000JAGUAR94,000JAG0009I,000JQQ0009O,000JAGUAR6Y,000JAGUAR7H,000JAGUAR7I,000JAKAAL7J,000BAKAAL7K,000JAGUAR7L";
String[] elements = original.split(",");
System.out.println(Arrays.toString(elements));

JSON Null Pointer Exception in Array with Jackson ObjectMapper

I am getting an array size of zero for the "tweets" array when trying to access the arraylist that it should be stored in. I am using Jackon databinding to a class, which at this point has "worked" as in not gave any errors or exceptions. But, the problem is still that the array is returning empty.
Here is the method where I am accessing the class that the JSON is being binded to:
WeatherDatabaseCreator.java
//Read in files to be parsed.
for (int i = 0; i < twitterFiles.size(); i++) {
File twitterFile = twitterFiles.get(i);
WeatherTweetParser wtp = new WeatherTweetParser(twitterFile);
wtp.mapJavaObject();
tws = new Tweets();
tweets = tws.getTweets();
System.out.print(tweets.size());
tweetIndex = 0;
System.out.println("Parsing and inserting twitter file '" + twitterFile.getAbsolutePath() + "'...");
//Step through all the tweets in each file, using the TweetParser class.
while (true) {
tweet = tweets.get(tweetIndex);
user = tweet.new User();
entity = tweet.new Entities();
userMentions = entity.getUserMentions();
hashtags = entity.getHashtags();
if (tweet.getText() == null) {
break;
}
numParsed++;
Boolean success = wdbm.insertTweet(tweet, user);
if (success == true) {
numInserted++;
}
if (entity.getNumHashtags() > 0){
for (int j = 0; j < entity.getNumHashtags(); j++) {
wdbm.insertHashtag(tweet, hashtags.get(j));
}
}
if (entity.getNumUserMentions() > 0) {
for (int k = 0; k < entity.getNumUserMentions(); k++) {
wdbm.insertReference(tweet, userMentions.get(k));
}
}
if (numParsed % UPDATE_INTERVAL == 0) {
System.out.println(numParsed + " tweets parsed. " + numInserted + " tweets inserted into database...");
}
tweetIndex++;
}
Here is part of the JSON File. The file is made up of an array of tweets, with some nested classes. Here I included two elements of the array:
2014-01-03-11-03.terms.json
{
"tweets": [
{
"filter_level": "medium",
"contributors": null,
"text": "U know your ice fishing at home when ur snacks are sandwiches,chips,dips,beef jerky and all the goodies instead of just a case of beer #mom",
"geo": null,
"retweeted": false,
"in_reply_to_screen_name": null,
"truncated": false,
"lang": "en",
"entities": {
"symbols": [
],
"urls": [
],
"hashtags": [
{
"text": "mom",
"indices": [
135,
139
]
}
],
"user_mentions": [
]
},
"in_reply_to_status_id_str": null,
"id": 419137025376145408,
"source": "<a href=\"http://twitter.com/download/iphone\" rel=\"nofollow\">Twitter for iPhone<\/a>",
"in_reply_to_user_id_str": null,
"favorited": false,
"in_reply_to_status_id": null,
"retweet_count": 0,
"created_at": "Fri Jan 03 16:03:48 +0000 2014",
"in_reply_to_user_id": null,
"favorite_count": 0,
"id_str": "419137025376145408",
"place": null,
"user": {
"location": "",
"default_profile": false,
"profile_background_tile": true,
"statuses_count": 5411,
"lang": "en",
"profile_link_color": "17EBCF",
"profile_banner_url": "https://pbs.twimg.com/profile_banners/408240224/1384838946",
"id": 408240224,
"following": null,
"protected": false,
"favourites_count": 4222,
"profile_text_color": "333333",
"description": "It is what it is, no more, no less. Trust in the Lord. BSU Softball #5. My whole being is happy - Psalm 16:9",
"verified": false,
"contributors_enabled": false,
"profile_sidebar_border_color": "FFFFFF",
"name": "Nicole Anne",
"profile_background_color": "C0DEED",
"created_at": "Wed Nov 09 05:03:58 +0000 2011",
"default_profile_image": false,
"followers_count": 452,
"profile_image_url_https": "https://pbs.twimg.com/profile_images/413270299925164033/mWiJBKP2_normal.jpeg",
"geo_enabled": true,
"profile_background_image_url": "http://a0.twimg.com/profile_background_images/698793822/14d9ce538d96b435ad4449d5385a3ec1.jpeg",
"profile_background_image_url_https": "https://si0.twimg.com/profile_background_images/698793822/14d9ce538d96b435ad4449d5385a3ec1.jpeg",
"follow_request_sent": null,
"url": null,
"utc_offset": -32400,
"time_zone": "Alaska",
"notifications": null,
"profile_use_background_image": true,
"friends_count": 634,
"profile_sidebar_fill_color": "DDEEF6",
"screen_name": "NDupay",
"id_str": "408240224",
"profile_image_url": "http://pbs.twimg.com/profile_images/413270299925164033/mWiJBKP2_normal.jpeg",
"listed_count": 1,
"is_translator": false
},
"coordinates": null
},
{
"filter_level": "medium",
"contributors": null,
"text": "Just watched DeBlasio shovel snow for the cameras and I have to say, his form is terrible. Looks a bit inexperienced.",
"geo": null,
"retweeted": false,
"in_reply_to_screen_name": null,
"truncated": false,
"lang": "en",
"entities": {
"symbols": [
],
"urls": [
],
"hashtags": [
],
"user_mentions": [
]
},
"in_reply_to_status_id_str": null,
"id": 419137026458673152,
"source": "<a href=\"http://twitter.com/download/iphone\" rel=\"nofollow\">Twitter for iPhone<\/a>",
"in_reply_to_user_id_str": null,
"favorited": false,
"in_reply_to_status_id": null,
"retweet_count": 0,
"created_at": "Fri Jan 03 16:03:48 +0000 2014",
"in_reply_to_user_id": null,
"favorite_count": 0,
"id_str": "419137026458673152",
"place": null,
"user": {
"location": "",
"default_profile": false,
"profile_background_tile": false,
"statuses_count": 2609,
"lang": "en",
"profile_link_color": "FF8000",
"id": 163686045,
"following": null,
"protected": false,
"favourites_count": 204,
"profile_text_color": "333333",
"description": "Love learning, Hockey #NYR, music and photography. My family is my whole life.",
"verified": false,
"contributors_enabled": false,
"profile_sidebar_border_color": "EEEEEE",
"name": "Steven Marques",
"profile_background_color": "ACDED6",
"created_at": "Wed Jul 07 01:26:25 +0000 2010",
"default_profile_image": false,
"followers_count": 56,
"profile_image_url_https": "https://pbs.twimg.com/profile_images/378800000795958214/5e3ff928282ad692a36e941e5c5ff628_normal.jpeg",
"geo_enabled": false,
"profile_background_image_url": "http://abs.twimg.com/images/themes/theme18/bg.gif",
"profile_background_image_url_https": "https://abs.twimg.com/images/themes/theme18/bg.gif",
"follow_request_sent": null,
"url": null,
"utc_offset": -18000,
"time_zone": "Eastern Time (US & Canada)",
"notifications": null,
"profile_use_background_image": true,
"friends_count": 58,
"profile_sidebar_fill_color": "F6F6F6",
"screen_name": "SMGafanha",
"id_str": "163686045",
"profile_image_url": "http://pbs.twimg.com/profile_images/378800000795958214/5e3ff928282ad692a36e941e5c5ff628_normal.jpeg",
"listed_count": 2,
"is_translator": false
},
"coordinates": null
},
Here is the Java class that the JSON file is mapped to, followed by the class mapping the JSON to the class:
Tweets.java
public class Tweets {
private ArrayList<Tweet> tweets;
public Tweets() {
tweets = new ArrayList<Tweet>();
}
public ArrayList<Tweet> getTweets() {
return tweets;
}
public void setTweets(ArrayList<Tweet> tweets) {
this.tweets = tweets;
}
public static class Tweet {
private String text;
#JsonProperty("source")
private String postMethod;
#JsonProperty("created_at")
private String time;
#JsonProperty("id")
private String ID;
public Tweet() {
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public String getID() {
return ID;
}
public void setID(String iD) {
ID = iD;
}
public String getPostMethod() {
return postMethod;
}
public void setPostMethod(String postMethod) {
this.postMethod = postMethod;
}
public String getTime() {
return time;
}
public void setTime(String time) {
this.time = time;
}
public class User {
private String location;
#JsonProperty("screen_name")
private String user;
#JsonProperty("time_zone")
private String timeZone;
#JsonProperty("description")
private String accountDescription;
public User(){
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
public String getUser() {
return user;
}
public void setUser(String user) {
this.user = user;
}
public String getTimeZone() {
return timeZone;
}
public void setTimeZone(String timeZone) {
this.timeZone = timeZone;
}
public String getAccountDescription() {
return accountDescription;
}
public void setAccountDescription(String accountDescription) {
this.accountDescription = accountDescription;
}
}
public class Entities {
#JsonProperty("user_mentions")
ArrayList<UserMention> userMentions;
#JsonProperty("hashtags")
ArrayList<Hashtag> hashtags;
public Entities() {
}
public ArrayList<UserMention> getUserMentions() {
return userMentions;
}
public int getNumUserMentions() {
return userMentions.size();
}
public UserMention getUserMention(int index) {
return userMentions.get(index);
}
public void setUserMentions(ArrayList<UserMention> userMentions) {
this.userMentions = userMentions;
}
public ArrayList<Hashtag> getHashtags() {
return hashtags;
}
public int getNumHashtags() {
return hashtags.size();
}
public Hashtag getHashtag(int index) {
return hashtags.get(index);
}
public void setHashtags(ArrayList<Hashtag> hashtags) {
this.hashtags = hashtags;
}
public class UserMention {
#JsonProperty("screen_name")
private String userRef;
public UserMention() {
}
public String getUserRef() {
return userRef;
}
public void setUserRef(String userRef) {
this.userRef = userRef;
}
}
public class Hashtag {
#JsonProperty("text")
private String hashText;
public Hashtag() {
}
public String getHashText() {
return hashText;
}
public void setHashText(String hashText) {
this.hashText = hashText;
}
}
}
}
}
WeatherTweetParser.java
public class WeatherTweetParser {
private static File twitterFile;
public WeatherTweetParser(File twitterFile) {
WeatherTweetParser.twitterFile = twitterFile;
}
public void mapJavaObject() {
String jsonFile = twitterFile.getName();
System.out.println("Mapping JSON to WeatherTweet Class.");
ObjectMapper mapper = new ObjectMapper();
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
try {
mapper.readValue(new File(jsonFile), Tweets.class);
} catch (JsonParseException e) {
e.printStackTrace();
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("Finished Mapping of JSON File.");
}
And here is the error:
Mapping JSON to WeatherTweet Class.
Finished Mapping of JSON File.
Tweets size: 0
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
at java.util.ArrayList.rangeCheck(Unknown Source)
at java.util.ArrayList.get(Unknown Source)
at database.WeatherDatabaseCreator.main(WeatherDatabaseCreator.java:145)
Parsing and inserting twitter file 'C:\Users\Jared\Documents\Eclipse
WorkSpace\workspace\WeatherDatabaseCreator\2014-01-03-11-03.terms.json'...
On this line of WeatherDatabaseCreator.java:
tweet = tweets.get(tweetIndex);
TL:DR: I understand this error is because the index is out of range, because there is nothing obviously even in the tweets array. But, if the Jackson mapping of the JSON file to my Java Class went through without exceptions, why is the tweets array empty?
while (true) {
tweet = tweets.get(tweetIndex);
user = tweet.new User();
entity = tweet.new Entities();
userMentions = entity.getUserMentions();
hashtags = entity.getHashtags();
if (tweet.getText() == null) {
break;
}
The only break in this loop will work only if getText is null. If getText is not null for all the tweets, you'll get index out of bound exception.
Instead of while(true) you should probably use a check like tweetIndex < tweets.size()
The second problem. You create a Tweets object without loading any items there:
wtp.mapJavaObject();
tws = new Tweets();
tweets = tws.getTweets();
Of course tws object will not have any tweets in this case. What you need to do is to make sure that your mapJavaObjects() method returns a Tweets object with the tweets loaded by ObjectMapper and after this is done your code should look like this:
tweets = wtp.mapJavaObject();
Something like this:
public Tweets mapJavaObject() {
String jsonFile = twitterFile.getName();
Tweets ret = null;
System.out.println("Mapping JSON to WeatherTweet Class.");
ObjectMapper mapper = new ObjectMapper();
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
try {
ret = (Tweets) mapper.readValue(new File(jsonFile), Tweets.class);
} catch (JsonParseException e) {
e.printStackTrace();
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("Finished Mapping of JSON File.");
retrun ret;
}

Categories

Resources