how to Iterate JsonArray using java 8 - java

I have Json array as below
{ "template": { "data": [{ "name": "customerGroupId", "value": "" }, { "name": "assetIntegrationId", "value": "" }, { "name": "problemCategory", "value": "" }, { "name": "problemSubCategory", "value": "" }, { "name": "resolutionCode", "value": "" }, { "name": "resolutionSubCode", "value": "" }, { "name": "imei", "value": "" }, { "name": "make", "value": "" }, { "name": "model", "value": "" }] } }
I am using following code to get values.
JSONArray jsonArray = jsonObject.getJSONObject("template").getJSONArray("data");
for (int i = 0; i < jsonArray.size(); i++) {
JSONObject jsonObjectData = jsonArray.getJSONObject(i);
if ("customerGroupId".equals(jsonObjectData.get("name"))) {
customerBean.setCustomerGroupId(jsonObjectData.get(VALUE).toString());
LOGGER.debug("JSON customerGroupId " + jsonObjectData.get(VALUE).toString());
} else if ("assetIntegrationId".equals(jsonObjectData.get("name"))) {
customerBean.setAssetIntegrationId(jsonObjectData.get(VALUE).toString());
LOGGER.debug("JSON assetIntegrationId " + jsonObjectData.get(VALUE).toString());
} else if ("problemCategory".equals(jsonObjectData.get("name"))) {
customerBean.setProblemCategory(jsonObjectData.get(VALUE).toString());
LOGGER.debug("JSON problemCategory " + jsonObjectData.get(VALUE).toString());
} else if ("problemSubCategory".equals(jsonObjectData.get("name"))) {
customerBean.setProblemSubCategory(jsonObjectData.get(VALUE).toString());
LOGGER.debug("JSON problemSubCategory " + jsonObjectData.get(VALUE).toString());
} else if ("resolutionCode".equals(jsonObjectData.get("name"))) {
customerBean.setResolutionCode(jsonObjectData.get(VALUE).toString());
LOGGER.debug("JSON resolutionCode " + jsonObjectData.get(VALUE).toString());
}
As the code has become repetitive,Is there any way in Java 8 or Java to avoid repetition of code.

You can try to use introspector or reflection.
And use name to find property or field.
Introspector:
JSONArray json = new JSONArray();
CustomerBean customerBean = new CustomerBean();
for (int i = json.size() - 1; i >= 0; i--) {
JSONObject data = json.getJSONObject(i);
PropertyDescriptor propDesc = new PropertyDescriptor(data.getString("name"), CustomerBean.class);
Method methodWriter = propDesc.getWriteMethod();
methodWriter.invoke(customerBean, data.getString("value"));
}
Reflection:
JSONArray json = new JSONArray();
CustomerBean customerBean = new CustomerBean();
for (int i = json.size() - 1; i >= 0; i--) {
JSONObject data = json.getJSONObject(i);
Field field = CustomerBean.class.getDeclaredField(data.getString("name"));
field.set(customerBean, data.get("data"));
}

Related

Fetching values and sending in an array

I have fetched some integer values from getAPI:
List<String> jsonResponse = response.jsonPath().getList("$");
for (int i = 0; i < jsonResponse.size(); i++) {
if (getJsonPath(response, "type[" + i + "]").equals("agent_sms_missed_call")) {
agentMissedCallId = getJsonPath(response, "id[" + i + "]");
break;
}
}
for (int i = 0; i < jsonResponse.size(); i++) {
if (getJsonPath(response, "type[" + i + "]").equals("caller_sms_missed_call")) {
callerMissedCallSmsId = getJsonPath(response, "id[" + i + "]");
break;
}
}
Now I want to send the value of agentMissedCallId and callerMissedCallSmsId in PUT API : How can i acheive that .
{
"sms_template": [
idFetched(agentMissedCallId), idFetched(callerMissedCallSmsId)
]
}
Response I am getting from a GET API :
[
{
"id": 29169,
"name": "Template 1",
"type": "agent_sms_missed_call"
},
{
"id": 29170,
"name": "Template 2",
"type": "caller_sms_missed_call"
}
]
Request body I want :
{
"sms_template": [
29169
],
"name": "Hello ",
"destination": "hangup||1",
"description": "number for department"
}
This below approach is not recommended, but it doesn't require any 3rd lib, so I think it works for you.
Map<String, Object> body = new LinkedHashMap<>();
body.put("sms_template", List.of(agentMissedCallId, callerMissedCallSmsId));
body.put("name", "Hello ");
body.put("destination", "hangup||1");
body.put("description", "number for department");
given().log().body().contentType(ContentType.JSON)
.body(body)
.post("https://postman-echo.com/post");

Get specific index of JSON Nested objects in java Android

How I can get only the "name" string of every object under "fields" Array, of main Array index at 0 & then next index using loop or with something super idea
[
{
"name": "Bank1",
"fields": [
{
"name": "Email",
"slug": "email",
"type": "input"
},
{
"name": "City",
"slug": "city",
"type": "input"
},
{
"name": "Screenshot",
"slug": "screenshot",
"type": "file"
},
{
"name": "Full Name",
"slug": "full-name",
"type": "input"
}
],
"status": "Active"
},
{
"name": "Bank2",
"fields": [
{
"name": "Email",
"slug": "email",
"type": "input"
},
{
"name": "City",
"slug": "city",
"type": "input"
},
{
"name": "Screenshot",
"slug": "screenshot",
"type": "file"
},
{
"name": "Submitted Date",
"slug": "submitted-date",
"type": "calendar"
}
],
"status": "Active"
}
]
Output I want:
Email
City
Screenshot
Full Name
Means in the output, I have got index 0, first object array data...
What I have done yet
public void onResponse(String response) {
try {
JSONArray jsonArray = new JSONArray(response);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
String p_name = jsonObject.getString("name");
ArrayList<String> arr = new ArrayList<>();
JSONArray ja = jsonObject.getJSONArray("fields");
int len = ja.length();
for (int j = 0; j < len; j++) {
JSONObject json = ja.getJSONObject(j);
arr.add(json.getString("name"));
}
}}catch block...
this gives me all indexes name data i want only specific index data
My Current Output:
Email
City
Screenshot
Full Name
Email
City
Screenshot
Submitted Date
If you want to get specific index data then you should pass if condition in for loop.
EX: to get output of index 0 like,
Email
City
Screenshot
Full Name
Your code would be like below.
public void onResponse(String response) {
try {
JSONArray jsonArray = new JSONArray(response);
for (int i = 0; i < jsonArray.length(); i++) {
if(i==0){
JSONObject jsonObject = jsonArray.getJSONObject(i);
String p_name = jsonObject.getString("name");
ArrayList<String> arr = new ArrayList<>();
JSONArray ja = jsonObject.getJSONArray("fields");
int len = ja.length();
for (int j = 0; j < len; j++) {
JSONObject json = ja.getJSONObject(j);
arr.add(json.getString("name"));
}
}
}}catch block...
int i=gotIndex;//here you can give your exact index that you want
JSONObject jsonObject = jsonArray.getJSONObject(i);
String p_name = jsonObject.getString("name");
ArrayList<String> arr = new ArrayList<>();
JSONArray ja = jsonObject.getJSONArray("fields");
int len = ja.length();
for (int j = 0; j < len; j++) {
JSONObject json = ja.getJSONObject(j);
arr.add(json.getString("name"));
}
here you used the loop you can use the json object out side the loop with using the index number i (jsonObject = jsonArray.getJSONObject(i))

Parsing multidimensional JSON array ERROR

Hi All I am trying to parse a JSON String that contains a multidimensional array. I keep getting the following error in the logs -> W/System.err: org.json.JSONException: No value for nutrients and this error corresponds to the following line -> JSONArray jsonArray1 = jsonObject.getJSONArray("nutrients");
Can someone please help me with this issue. thanks in advance
The JSON String I am trying to parse ->
{
"results": [
{
"id": 654959,
"title": "Pasta With Tuna",
"image": "https://spoonacular.com/recipeImages/654959-312x231.jpg",
"imageType": "jpg",
"nutrition": {
"nutrients": [
{
"title": "Calories",
"amount": 420.823,
"unit": "kcal"
},
{
"title": "Protein",
"amount": 24.4751,
"unit": "g"
},
{
"title": "Fat",
"amount": 10.3277,
"unit": "g"
},
{
"title": "Carbohydrates",
"amount": 57.6915,
"unit": "g"
}
]
}
}
My Java code to parse it ->
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray jsonArray = jsonObject.getJSONArray("results");
for (int i = 0; i < jsonArray.length(); i++) {
int id = jsonArray.getJSONObject(i).getInt("id");
String title = jsonArray.getJSONObject(i).getString("title");
String image = jsonArray.getJSONObject(i).getString("image");
Log.i("a", "" + title);
JSONArray jsonArray1 = jsonObject.getJSONArray("nutrients");
for(int e = 0; e < jsonArray1.length(); e++) {
JSONObject jsonObject1 = jsonArray1.getJSONObject(e);
double calories = jsonObject1.getDouble("amount");
Log.i("calories", "" + calories);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
Your JSON is invalid.
Here is a valid one
{
"results": [
{
"id": 654959,
"title": "Pasta With Tuna",
"image": "https://spoonacular.com/recipeImages/654959-312x231.jpg",
"imageType": "jpg",
"nutrition": {
"nutrients": [
{
"title": "Calories",
"amount": 420.823,
"unit": "kcal"
},
{
"title": "Protein",
"amount": 24.4751,
"unit": "g"
},
{
"title": "Fat",
"amount": 10.3277,
"unit": "g"
},
{
"title": "Carbohydrates",
"amount": 57.6915,
"unit": "g"
}
]
}
}
]
}
Then your Java code
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray jsonArray = jsonObject.getJSONArray("results");
JSONObject resultsObject=jsonArray.getJSONObject(0);
int id = resultsObject.getInt("id");
String title = resultsObject.getString("title");
String image =resultsObject.getString("image");
Log.i("a", "" + title);
JSONObject nutrition = resultsObject.getJSONObject("nutrition");
JSONArray nutrients = nutrition.getJSONArray("nutrients");
for(int e = 0; e < nutrients.length(); e++) {
JSONObject jsonObject1 = nutrients.getJSONObject(e);
double calories = jsonObject1.getDouble("amount");
Log.i("calories", "" + calories);
}
} catch (JSONException e) {
e.printStackTrace();
}
Hope Helpful!

I am getting error parsing the given value when tried to parse the given json format android

I have the below following type of json structure which is coming from url.
[{
"id": 1,
"name": "TV",
"fromcenter": {
"car": "60 Mins",
"bus": "20 Mins"
},
"location": {
"latitude": -33.7181,
"longitude": 10.3160
}
}, {
"id": 2,
"name": "Fridge",
"fromcenter": {
"car": "30 Mins"
},
"location": {
"latitude": -33.8433,
"longitude": 11.2411
}
}, {
"id": 3,
"name": "Mixie",
"fromcenter": {
"car": "20 Mins",
"bus": "40 Mins"
},
"location": {
"latitude": -3.8910,
"longitude": 11.27777
}
}]
I am able to parse everything except the "bus" because the bus is not available in id 2. So I am getting error as value "bus" not found. JSONException.
Let me know how to solve this? Below is what I tried.
try {
JSONArray array = new JSONArray(response);
goodModelArrayList = new ArrayList<>();
for (int i = 0; i < array.length(); i++) {
JSONObject e = array.getJSONObject(i);
spinnerModel = new MyTransport();
fromcenter = new Fromcenter();
location = new Location();
for (int j = 0; j < e.length(); j++) {
JSONObject object = e.getJSONObject("location");
latitude = object.getString("latitude");
longitude = object.getString("longitude");
}
for (int k = 0; k < e.length(); k++) {
JSONObject object = e.getJSONObject("fromcenter");
car = object.getString("car");
//bus = object.getString("bus"); //I am not able to get the bus. It throws JSONException error.
}
spinnerModel.setId(String.valueOf(e.getString("id")));
spinnerModel.setName(e.getString("name"));
spinnerModel.setFromcenter(car);
//spinnerModel.setBus(bus); //I am not able to store the datas.
spinnerModel.setLocation(latitude);
spinnerModel.setLocations(longitude);
goodModelArrayList.add(spinnerModel);
}
} catch (Exception e) {
e.printStackTrace();
}
you can interrogate if the object has the property before reading it
if (object.has("bus")) {
bus = object.getString("bus");
}
Straight forward one word.
Use optString instead of getString
optString eliminates this issue. Bus is not present in 2nd item.
So use
String bus= object.optString("bus");

JSON get Array without object

I'm trying to parse this JSON,
{
"listname": "red",
"lists": [
{
"id": "01",
"name": "paw",
"list": [
{
"id": "A",
"name": "pawa",
"bar": "foo"
},
{
"id": "B",
"name": "pawb",
"bar": "foo"
}
]
},
{
"id": "02",
"name": "pew",
"list": [
{
"id": "A",
"name": "pewa",
"bar": "foo"
},
{
"id": "B",
"name": "pewb",
"bar": "foo"
}
]
},
{
"id": "03",
"name": "piw",
"list": [
{
"id": "A",
"name": "piwa",
"bar": "foo"
},
{
"id": "B",
"name": "piwb",
"bar": "foo"
}
]
}
]
}
I put it on Asset Folder and I read it and it converts it to me to String since here all good, the problem is when I'm trying to get the name from each item of lists and trying to get all the names from the list I've tried it doing this :
JSONObject obj = new JSONObject(str);
JSONArray jsonMainArr = obj.getJSONArray("lists"); //first get the lists
for (int i = 0; i < jsonMainArr.length(); i++) {
JSONObject childJSONObject = jsonMainArr.getJSONObject(i);
String name = childJSONObject.getString("name");
Toast.makeText(context, name, Toast.LENGTH_SHORT).show();
}
JSONObject obj = new JSONObject(str);
JSONArray jsonMainArr = obj.getJSONArray("list"); //get the list
for (int i = 0; i < jsonMainArr.length(); i++) {
JSONObject childJSONObject = jsonMainArr.getJSONObject(i);
String name = childJSONObject.getString("name");
Toast.makeText(context, name, Toast.LENGTH_SHORT).show();
}
But it doesn't show anything... what I'm missing?
EDIT
This is how I read the JSON
public static String loadJSONFromAsset(Context ctx, String str) {
String json = null;
try {
InputStream is = ctx.getAssets().open(str);
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
json = new String(buffer, "UTF-8");
} catch (IOException ex) {
ex.printStackTrace();
return null;
}
return json;
}
Since your "list" is nested in the childJSONObject (from "lists") , nest your for loops to retrieve the this set of values (the JSONobject)
JSONObject obj = new JSONObject(str);
//first get the top-level "lists"
JSONArray jsonMainArr = obj.getJSONArray("lists");
for (int i = 0; i < jsonMainArr.length(); i++) {
JSONObject childJSONObject = jsonMainArr.getJSONObject(i);
String name = childJSONObject.getString("name");
Toast.makeText(context, name, Toast.LENGTH_SHORT).show();
//get the inner "list" from childJSONObject
JSONArray childJSONArray = childJSONObject.getJSONArray("list");
for (int j = 0; j < childJSONArray.length(); j++) {
JSONObject childJSONObjectB = childJSONArray.getJSONObject(j);
String name = childJSONObjectB.getString("name");
Toast.makeText(context, name, Toast.LENGTH_SHORT).show();
}
}

Categories

Resources