How can I get inside info object using volley in android java - 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();
}

Related

Map JSON array into java object array

I'm calling API and getting the response as a JSON array I need to map that array into Java object array. Here I've defined the model class below you can see API JSON array, Model class and the way I try to map JSON array into Java object array. I need to make sure if this approach is correct or not.
API response JSON array
[
{
"sanctionId": 594,
"listId": "SDN",
"listType": "SANCTION",
"publisher": "OFAC",
"addedDate": "2022-02-11T04:52:59.775+0000",
"programs": "CUBA",
"name": " CUBA CIGARS TRADE",
"title": null,
"type": "Entity",
"contacts": [
{
"id": 361,
"address": " ",
"city": "",
"state_province": "",
"country": "Italy",
"remarks": null
}
],
"identities": null,
"remarks": null,
"other": null,
"score": 2.1659167
},
{
"sanctionId": 602,
"listId": "SDN",
"listType": "SANCTION",
"publisher": "OFAC",
"addedDate": "2022-02-11T04:52:59.779+0000",
"programs": "CUBA",
"name": " CUBA N CIGARS TRADE",
"title": null,
"type": "Entity",
"contacts": [
{
"id": 361,
"address": " ",
"city": "",
"state_province": "",
"country": "Italy",
"remarks": null
}
],
"identities": null,
"remarks": null,
"other": null,
"score": 1.9129416
}
]
Model Class(here I've omitted getters and setters) :
public class SanctionInquiryResponse {
private String sanctionId="";
private String listId="";
private String listType="";
private String publisher="";
private String addedDate="";
private String programs="";
private String name="";
private String title="";
private String type="";
private String identities="";
private String remarks="";
private String other="";
private String score="";
private List<Contacts> contacts = null;
}
public class Contacts {
private String id = "";
private String address = "";
private String city = "";
private String state_Province = "";
private String country = "";
private String remarks = "";
}
Here is the way I'm trying to map the JSON array into the Java object array
String url="http://localhost:8070/getObject";
ObjectMapper mapper = new ObjectMapper();
//String jsonInString = mapper.writeValueAsString(openCaseRequest);
Client client = Client.create();
client.setConnectTimeout(120*1000);
client.setReadTimeout(120*1000);
WebResource webResource = client.resource(url);
ClientResponse response = webResource.type(MediaType.APPLICATION_JSON).post(ClientResponse.class);
String output = response.getEntity(String.class);
JSONArray jsonArray = new JSONArray(output);
Gson gson = new Gson();
for (int i = 0; i < jsonArray.length(); i++) {
sanctionInquiryResponse = gson.fromJson(jsonArray.getJSONObject(i).toString() ,SanctionInquiryResponse.class);
}

How to extract key value from a JSON response in Java Language? I want to extract the value of "doj" but I'm not able to do so

{
"reservation_upto": {
"lng": 78.0098161,
"lat": 27.1752554,
"code": "AGC",
"name": "AGRA CANTT"
},
"debit": 3,
"doj": "28-05-2018",
"to_station": {
"lng": 78.0098161,
"lat": 27.1752554,
"code": "AGC",
"name": "AGRA CANTT"
},
"response_code": 200,
"boarding_point": {
"lng": 80.2755685,
"lat": 13.081674,
"code": "MAS",
"name": "CHENNAI CENTRAL"
},
"pnr": "4405474586",
"chart_prepared": false,
"journey_class": {
"code": "3A",
"name": null
},
THIS IS WHAT I HAVE TRIED USING VOLLEY
private void loaddata() {
String url = "https://api.railwayapi.com/v2/pnr-status/pnr/4655474586/apikey/q15rfl3kpz/";
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
progressDialog.dismiss();
JSONObject obj = null;
try {
String str="";
obj = response.getJSONObject("name");
str = String.valueOf(obj);
TextView tv = (TextView)findViewById(R.id.textView);
tv.append(str);
}
}
}
}
}
JSONObject obj = (JSONObject) object;
String doj = (String) obj.get("doj")
You can use JSONObject obj to find out the value of key doj.
Latter on, if you want to have the doj as any other datatype you can parse in that. May be this could help. I don't have much idea on Volley :)

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());

JSON content from file via Java

My program parse JSON from file where is saved unstructured content of this json adress.
Unstructured json format from file json.txt:
{"total":3307,"watershed":100,"maxPage":5,"search":"http://10.103.80.149:3312/bin/sp?app=pinglun&outfmt=json&seek_timeout=400&gmt_create=1465228800~&validfeedback=1&item_id=538236063692&rate=1&layer_quota=500000&status=0,-1&order=algo_sort:des&s=0&n=20&is_wireless=0&user_id=0&utd_id=ba3290d86b9fdcd927e8ae83fde1ee64&is_click_sku=0","currentPageNum":1,"comments":[{"auction":{"title":"","thumbnail":""....
For better view in structured form:
{
"total": 3307,
"watershed": 100,
"maxPage": 5,
"search": "http://10.103.80.162:3312/bin/sp?app=pinglun&outfmt=json&seek_timeout=400&gmt_create=1465228800~&validfeedback=1&item_id=538236063692&rate=1&layer_quota=500000&status=0,-1&order=algo_sort:des&s=0&n=20&is_wireless=0&user_id=0&is_click_sku=0",
"currentPageNum": 1,
"comments": [
{
"auction": {
"title": "",
"thumbnail": "",
"aucNumId": "538236063692",
"link": "//item.taobao.com/item.htm?id=538236063692",
"auctionPic": "//img.alicdn.com/bao/uploaded/null_40x40.jpg",
"sku": "机身颜色:黑色(顶级配置)[移动+联通] &nbsp套餐类型:官方标配 &nbsp存储容量:64MB &nbsp版本类型:中国大陆"
},
"promotionType": "活动促销 ",
"enableSNS": false,
"tag": "",
"appendCanExplainable": false,
"showCuIcon": true,
"validscore": 1,
"award": "",
"noQna": true,
"appendList": [
{
"photos": [
],
"content": "老人机使用效果好,功能强大,非常值得拥有!!!",
"vicious": "",
"reply": null,
"show": true,
"dayAfterConfirm": 0,
"appendId": 290673146633
}
],
"from": "",
"date": "2016年11月05日 16:46",
"dayAfterConfirm": 0,
"bidPriceMoney": {
"cent": 7905,
"amount": 79.05,
"currencyCode": "CNY",
"centFactor": 100,
"displayUnit": "元",
"currency": {
"defaultFractionDigits": 2,
"currencyCode": "CNY",
"symbol": "¥"
}
},
"rate": "1",
"o2oRate": null,
"propertiesAvg": "0.0",
"showDepositIcon": false,
"rateId": 290589793921,
"creditFraudRule": 0,
"useful": 0,
"reply": null,
"append": {
"photos": [
],
"content": "老人机使用效果好,功能强大,非常值得拥有!!!",
"vicious": "",
.
.
.
.}
And I need to parse only chinese comments in element "content" e.g. "老人机使用效果好,功能强大,非常值得拥有!!!", but I don't know how to works with this element in JSONArray with json-simple.
Here is example of code:
public class Final {
public static void main(String[] args) throws IOException, JSONException {
String jsonData = "";
BufferedReader br = null;
try {
String line;
br = new BufferedReader(new FileReader("json.txt"));
while ((line = br.readLine()) != null) {
jsonData += line + "\n";
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null)
br.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
System.out.println("\nFile Content: \n" + jsonData1); // displays all content
JSONObject obj = new JSONObject(jsonData);
System.out.println("search: " + obj.getString("search"));
System.out.println("comments: " + obj.getJSONObject("comments"));
}
}
Could you please help me with this problem?

JAVA org.json not showing empty value

Here is my JAVA JSON code
#GET
#Consumes("application/x-www-form-urlencoded")
#Path("/getAllEmp")
public Response GetAllEmp() {
JSONObject returnJson = new JSONObject();
try {
ArrayList<Emp_Objects> objList = new ArrayList<Emp_Objects>();
DBConnection conn = new DBConnection();
objList = conn.GetEmpDetails();
JSONArray empArray = new JSONArray();
if (!objList.isEmpty()) {
GetLocation loc = new GetLocation();
for (Emp_Objects obj : objList) {
JSONObject jsonObj = new JSONObject();
jsonObj.put("id", obj.id);
jsonObj.put("name", obj.name);
jsonObj.put("email", obj.email);
jsonObj.put("address", obj.address);
empArray.put(jsonObj);
}
}
returnJson.put("data", empArray);
} catch (Exception e) {
}
return Response.ok(returnJson.toString()).header("Access-Control-Allow-Origin", "*").build();
}
When i execute this it gives me the following json
{
"data": [{
"id": 1,
"name": "123_name"
}, {
"id": 2,
"name": "321_name",
"email": "xyz#asd.com"
}]
}
In the above json email and address are missing because email and address is null on database.
So can i show json with empty value like following
{
"data": [{
"id": 1,
"name": "123_name",
"email": "",
"address": ""
}, {
"id": 2,
"name": "321_name",
"email": "",
"address": ""
}]
}
I am using JAVA and org.json with MySQL database.
If the objects are null, insert an empty String instead.
jsonObj.put("email", obj.email == null ? "" : obj.email);
jsonObj.put("address", obj.address == null ? "" : obj.address);
If you have a larger amount of rows to process, I recommend you to turn this is to a function for better readability and to save you some time.
jsonObj.put("email", nullToEmpty(obj.address));
private String nullToEmpty(String arg) {
return arg == null ? "" : arg;
}

Categories

Resources