How to parse json response with array list - java

I have a below response which I am unable to validate due to response is starting from JSON object 0. Thats means if more than one object, the response will start from 0 to the number of objects you have.
I have tried this but its not working and ends up with stack over flow error.
public static void Location_ContactValidation(Response response, String code, String message, ExtentTest log) {
try {
softAssert = new SoftAssert();
org.json.JSONObject jsonObject = new org.json.JSONObject(response);
org.json.JSONObject getSth = jsonObject.getJSONObject("status");
status_Message = getSth.get("message");
softAssert.assertEquals(code, code);
softAssert.assertEquals(message, status_Message);
log.log(LogStatus.INFO, "Validation: The status code is " + code);
log.log(LogStatus.INFO, "Validation: The status message is " + status_Message.toString());
} catch (Exception e) {
log.log(LogStatus.INFO, "Validation: The status code is " + code);
if (status_Message != null) {
log.log(LogStatus.INFO, "Validation: The status message is " + status_Message.toString());
}
System.out.println(e.getMessage());
if (softAssert != null) {
softAssert.assertAll();
}
}
}
Stack overflow error as flows-
java.lang.StackOverflowError
at org.json.JSONObject.wrap(JSONObject.java:1746)
at org.json.JSONArray.<init>(JSONArray.java:176)
at org.json.JSONObject.wrap(JSONObject.java:1747)
at org.json.JSONObject.populateMap(JSONObject.java:1167)
And here is the response I want to parse
{
"0": {
"status": "OK",
"data": {
"id": "*************",
"mobile": "*************"
},
"message": "Submitted Successfully"
},
"status": "OK"
}
I need to validate the mobile number, both the status and message.
But not able to do it.
If one more number is send with request then the response increases and to array gets created first as shown with 0 then with 1.
I appreciate your help.

You can list all keys for given JSONObject using keySet method. After that you can directly dig into required fields.
Below codes shows how to read all required fields:
import org.json.JSONObject;
import java.io.File;
import java.nio.file.Files;
public class OrgJsonApp {
public static void main(String[] args) throws Exception {
File jsonFile = new File("./resource/test.json").getAbsoluteFile();
String json = String.join("", Files.readAllLines(jsonFile.toPath()));
JSONObject response = new JSONObject(json);
response.keySet().forEach(key -> {
JSONObject object = response.optJSONObject(key);
// if given key represents object it must be data
if (object != null) {
final String dataKey = "data";
JSONObject data = object.optJSONObject(dataKey);
// extract mobile from data and remove data
// this way JSON node is much simpler
if (data != null) {
final String mobileKey = "mobile";
String mobile = data.optString(mobileKey);
System.out.println("Mobile => " + mobile);
}
System.out.println("status => " + object.optString("status"));
System.out.println("message => " + object.optString("message"));
}
});
}
}
For below JSON payload:
{
"0": {
"status": "OK",
"data": {
"id": "1",
"mobile": "44-32-12"
},
"message": "Submitted Successfully"
},
"1": {
"status": "OK",
"data": {
"id": "2",
"mobile": "9981234-543"
},
"message": "Submitted Successfully"
},
"status": "OK"
}
prints:
Mobile => 44-32-12
status => OK
message => Submitted Successfully
Mobile => 9981234-543
status => OK
message => Submitted Successfully

Related

JSON file processing with a different structure

I have an android app (Java) that processes an API from te web.
Currently the app is processing a JSON file that looks like this:
{
"contacts": [
{
"id": 1,
"name": "name1",
"email": "email1",
"phone": "1234567890"
},
{
"id": 2,
ETC...
I need to process another JSON file but it has a different structure:
{
"contacts": {
"1": {
"id": 1,
"name": "name1",
"email": "email1",
"phone": "1234567890",
"level1": {
"level2": {
"level3": 3,
}
},
"last_updated": 20180712
},
"2": {
ETC...
How do I process this second JSON file by adjusting the below code?
if (jsonSource != null) {
try {
JSONObject jsonObject = new JSONObject(jsonSource);
JSONArray jsonArrayData = jsonObject.getJSONArray("contacts");
for (int i = 0; i < jsonArrayData.length(); i++) {
JSONObject contacts = jsonArrayData.getJSONObject(i);
String id = contacts.getString("id");
String name = contacts.getString("name");
String email = contacts.getString("email");
String phone = contacts.getString("phone");
HashMap<String, String> values = new HashMap<>();
values.put("id", id);
values.put("name", name);
values.put("email, email);
values.put("phone, phone);
contactList.add(values);
}
} catch (final JSONException e) {
Log.e(TAG, "JSON parsing error: " + e.getMessage());
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getContext(), "ERROR", Toast.LENGTH_LONG).show();
}
});
}
} else {
Log.e(TAG, "Unable to retrieve JSON file from URL");
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getContext(), "ERROR", Toast.LENGTH_LONG).show();
}
});
}
return null;
Any help is much appreciated!
It looks, that inside first json you have "contacts" as array of objects, and inside second one you have "contacts" as object. Inside it you have other objects, simplified version looks like this:
"contacts": [
{...},
{...},
{...}
]
"contacts": {
"1": {...},
"2": {...},
"3": {...}
}
So, the only option you have is to check manually is "contacts" array or object, and based on it change your code.
It would look like this:
JSONObject jsonObject = new JSONObject(jsonSource);
if (jsonObject.get("contacts") instanceof JSONObject) {
JSONObject contactsJson = jsonObject.getJSONObject("contacts");
for (Iterator<String> it = contactsJson.keys(); it.hasNext(); ) {
String key = it.next();
JSONObject contactJson = contactsJson.getJSONObject(key);
// your code to process contact item
}
} else {
// Your code to process every contact item
}

Inserting into document elasticsearch java API not working

So I am just trying to add data in my indice via java transport client api . My code runs without any exceptions.
It successfully connects to my server, I can see the connection details on my console.
I listed all indices available on the server and it did show that too.
Then I tried to insert docs into my indice called logs
code runs without any exceptions.
I am lost here and have no idea what I am missing. The data is not getting inserted in the indice. Any help is appreciated.
Below is my code :
public static void main(String[] args) {
try {
ElasticSearchMain es = new ElasticSearchMain();
ElasticSearchMain.configureClient();
JSONObject data = new JSONObject();
data.put("serverip", "bhavik");
data.put("classname", "bhavik");
data.put("methodname", "bhavik");
data.put("exception", "bhavik");
data.put("logexception", "4896681231231232");
data.put("timestamp", "1900-00-00");
es.setIndex(data.toString(), "logs");
} catch (Exception e) {
e.printStackTrace();
}
}
public IndexRequestBuilder setIndex(String data,String IndexName){
try{
return client.prepareIndex(IndexName, "event").setSource(data);
}catch(Exception e){
e.printStackTrace();
}
return null;
}
public static void configureClient(){
try{
if(client==null){
String address = "localhost";
int port = 9300;
BasicConfigurator.configure();
client = TransportClient.builder().build()
.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName(address), port));
String[] indices = client.admin().indices().getIndex(new GetIndexRequest()).actionGet().getIndices();
for (String s : indices) {
System.out.println("indice ->> " + s);
}
}
}catch(Exception e ){
e.printStackTrace();
EmgrLog.AppendExceptionToLog(e);
}
}
Indice mapping :
PUT logs
{
"mappings": {
"event": {
"properties": {
"serverip": {
"type": "integer",
"index": "not_analyzed"
},
"classname": {
"type": "string",
"analyzer": "english"
},
"methodname": {
"type": "string",
"index": "not_analyzed"
},
"exception": {
"type": "string",
"index": "not_analyzed"
},
"logexception": {
"type": "string"
},
"timestamp":{
"type": "date"
}
}
}
}
}
This code :
public IndexRequestBuilder setIndex(String data,String IndexName){
try{
return client.prepareIndex(IndexName, "event").setSource(data);
}catch(Exception e){
e.printStackTrace();
}
return null;
}
Returns a "request builder", but this request is never built, nor executed, and logically, nothing happens as a consequence.
To submit the request, you have to send it to the elasticsearch instance.
Elasticsearch JavaAPI documentation proposes this code :
IndexResponse response = client.prepareIndex("twitter", "tweet", "1")
.setSource(jsonBuilder()
.startObject()
.field("user", "kimchy")
.field("postDate", new Date())
.field("message", "trying out Elasticsearch")
.endObject()
)
.get();
Note the get() at the end of the snippet is what triggers the call.

Retrofit 2.0 get array of json object as a result of post request

I have a response form server as :
[
{
"ID": "1",
"Title": "BIRATNAGAR",
"BankID": "1",
"BranchCode": "0",
"LocationID": "71500200",
"IsActive": "yes"
},
{
"ID": "2",
"Title": "BIRATNAGAR",
"BankID": "1",
"BranchCode": "0",
"LocationID": "71500900",
"IsActive": "yes"
},
{
"ID": "3",
"Title": "BIRATNAGAR",
"BankID": "1",
"BranchCode": "0",
"LocationID": "94361117",
"IsActive": "yes"
}
]
I have retrofit api as:
#POST("authapp/Restserver/api/Masterdata/getBranchListByBank")
Call> getBranchListByBank(#Query("api_key") String id);
I have called it as:
RetrofitArrayAPI service = retrofit.create(RetrofitArrayAPI.class);
Call<List<BankBranch>> call = service.getBranchListByBank(s);
call.enqueue(new Callback<List<BankBranch>>() {
#Override
public void onResponse(Call<List<BankBranch>> call, Response<List<BankBranch>> response) {
try {
List<BankBranch> banks = response.body();
for (int i = 0; i < banks.size(); i++) {
String id = banks.get(i).getTitle();
String name = banks.get(i).getID();
String marks = banks.get(i).getIsActive();
Log.i("ashihs", id + " " + marks + " " + name);
}
} catch (Exception e) {
Log.d("onResponse", "There is an error");
e.printStackTrace();
}
}
#Override
public void onFailure(Call<List<BankBranch>> call, Throwable t) {
Log.d("onFailure", t.toString());
}
});
But I cannot get the list of the bank branch. I get error as :
java.lang.IllegalStateException: Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 2 path $
Can any one help me?
Thanks in advance.
U probably got bad Api request it schould look like this:
api:
#POST("authapp/Restserver/api/Masterdata/getBranchListByBank")
Call<List<BankBranch>> getBranchListByBank(#Query("api_key") String id);
And the method schould look like this:
Call<List<BankBranch>> response = apiCall.getBranchListByBank(id);
response.enqueue(new Callback<List<BankBranch>>() {
#Override
public void onResponse(Call<List<BankBranch>> call, Response<List<BankBranch>> response) {
List<BankBranch> bankBranch = response.body();
}
#Override
public void onFailure(Call<List<BankBranch>> call, Throwable t) {
}
});
}
make sure Your model BankBranch fit the JSON response;

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;
}

How to parse the json object with multiple keys in android

I want to put the JSON result in textviews but because of multiple array i can get only one key/value of datetime, location and status objects. The json object is:
{
"signature":"testSignature",
"deliverydate":"2015-08-06 15:07:00",
"datetime":{
"0":1438848420,
"1":1438841820,
"2":1438838760,
},
"location":{
"0":"PA",
"1":"PA",
"2":"PA",
},
"status":{
"0":"packed",
"1":"On the go",
"2":"delivered",
},
"pickupdate":2015-08-04 07:55:00
}
and this is my java code:
try {
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("NO", NUMBER_TO_POST));
JSONObject json = jsonParser.makeHttpRequest(URL_TO_POST, "POST", params);
success = json.getString(TAG_SIGNATURE);
if (success != null) {
SIGNATURE = json.getString(TAG_SIGNATURE);
DELIVERY_DATE = json.getString(TAG_DELIVERY_DATE);
JSONObject DT = json.getJSONObject(TAG_DATETIME);
DATETIME = DT.getString("0");
JSONObject LOC = json.getJSONObject(TAG_LOCATION);
LOCATION = LOC.getString("0");
JSONObject STAT = json.getJSONObject(TAG_STATUS);
STATUS = STAT.getString("0");
PICKUP_DATE = json.getString(TAG_PICKUP_DATE);
}else{
finish();
}
} catch (JSONException e) {
e.printStackTrace();
}
can anyone help me to solve this? Thanks
You should use GSON library to parse JSONs.
And to be a bit more helpful, here is how your class to hold JSON values might look like:
class MyClassForGsonToHoldParseJSON {
String signature;
String deliverydate;
Map<String, long> datetime;
Map<String, String> location;
Map<String, String> status;
String pickupdate;
}
Then just use something like this to conver variable json with JSON data to an object:
Gson gson = new Gson();
MyClassForGsonToHoldParseJSON f = gson.fromJson(json, MyClassForGsonToHoldParseJSON.class);
Your JSON format is wrong:
{
"signature": "testSignature",
"deliverydate": "2015-08-06 15:07:00",
"datetime": {
"0": 1438848420,
"1": 1438841820,
"2": 1438838760
},
"location": {
"0": "PA",
"1": "PA",
"2": "PA"
},
"status": {
"0": "packed",
"1": "On the go",
"2": "delivered"
},
"pickupdate": " 2015-08-04 07:55:00"
}

Categories

Resources