I need to implement below json payload to java object including JSONArray and JSONObject
I tried using below java code in order to implement the same
DWYT_productOrderResponse CreateProductOrderResponse = new DWYT_productOrderResponse();
ResultHeader rslthdr = new ResultHeader();
JSONObject productOrder = new JSONObject();
JSONArray orderIt = new JSONArray();
JSONObject produt = new JSONObject();
// List<ProductCharacteristic> ProductChara = new ArrayList<ProductCharacteristic>();
Map ProductChara = new LinkedHashMap();
//Map orderItem = new LinkedHashMap();
// OrderIteam[] orderItem;
if (1 == 1) {
String output = null;
try {
productOrder.put("externalId", CreateOrderReq.getProductOrder().getExternalId());
productOrder.put("description", CreateOrderReq.getProductOrder().getDescription());
ProductChara.put("name", "CustomerName");
ProductChara.put("value", CreateOrderReq.getProductOrder().getOrderItem().getProduct().getProductCharacteristic().getCustomerName());
ProductChara.put("name", "CustomerContactNumber");
ProductChara.put("value", CreateOrderReq.getProductOrder().getOrderItem().getProduct().getProductCharacteristic().getCustomerContactNumber());
ProductChara.put("name", "CRMAddress");
ProductChara.put("value", CreateOrderReq.getProductOrder().getOrderItem().getProduct().getProductCharacteristic().getCRMAddress());
ProductChara.put("name", "CustomerEmail");
ProductChara.put("value", CreateOrderReq.getProductOrder().getOrderItem().getProduct().getProductCharacteristic().getCustomerEmail());
ProductChara.put("name", "CustomerGovetID");
ProductChara.put("value", CreateOrderReq.getProductOrder().getOrderItem().getProduct().getProductCharacteristic().getCustomerGovtID());
ProductChara.put("name", "ODBNo");
ProductChara.put("value", CreateOrderReq.getProductOrder().getOrderItem().getProduct().getProductCharacteristic().getODBNO());
produt.put("productCharacteristic", ProductChara);
produt.put("product", produt);
orderIt.put(produt);
productOrder.put("orderItem", orderIt);
productOrder.put("productOrder", productOrder);
} catch (JSONException e) {
e.printStackTrace();
}
}
here is the result of json payload of the above code
{
"externalId":"CRM000000912",
"description":"Activation Request",
"orderItem":[
{
"productCharacteristic":{
"name":"CustomerName",
"value":"xxxx",
"name":"CustomerContactNumber",
"value":"5600000232",
"name":"CRMAddress",
"value":"xxxxxxx",
"name":"CustomerEmail",
"value":"xxx#xx.xxx",
"name":"CustomerGovetID",
"value":"1223232323232322",
"name":"ODBNo",
"value":"RYH-736834-JKS"
}
}
]
}
here is the json payload that I want to parse
{
"externalId": " 12345678",
"orderItem": [{
"product": {
"productCharacteristic": [{
"name": "CustomerName",
"value": "someone"
}, {
"name":
"CustomerContactNumber",
"value": "13524687502"
}, {
"name": "CRMAddress",
"value": "xxxxxx"
}, {
"name": "CustomerEmail ",
"value": "XXX"
}, {
"name": " CustomerGovet.ID",
"value": "XXX"
}, {
"name": " ODBNo.",
"value": "XXX"
}
]
}
}
]
}
Is there any easy way or java code that can help me to get the expected output.
SOLVED: now I got the expected json payload after adding some enhancement to my code
try {
productOrder.put("externalId", CreateOrderReq.getProductOrder().getExternalId());
productOrder.put("description", CreateOrderReq.getProductOrder().getDescription());
ProductChara.put("name","CustomerName");
ProductChara.put("value",CreateOrderReq.getProductOrder().getOrderItem().getProduct().getProductCharacteristic().getCustomerName());
ProductCharaArray.put(ProductChara);
ProductChara.put("name","CustomerContactNumber");
ProductChara.put("value",CreateOrderReq.getProductOrder().getOrderItem().getProduct().getProductCharacteristic().getCustomerContactNumber());
ProductCharaArray.put(ProductChara);
ProductChara.put("name","CRMAddress");
ProductChara.put("value",CreateOrderReq.getProductOrder().getOrderItem().getProduct().getProductCharacteristic().getCRMAddress());
ProductCharaArray.put(ProductChara);
ProductChara.put("name","CustomerEmail");
ProductChara.put("value",CreateOrderReq.getProductOrder().getOrderItem().getProduct().getProductCharacteristic().getCustomerEmail());
ProductCharaArray.put(ProductChara);
ProductChara.put("name","CustomerGovetID");
ProductChara.put("value",CreateOrderReq.getProductOrder().getOrderItem().getProduct().getProductCharacteristic().getCustomerGovtID());
ProductCharaArray.put(ProductChara);
ProductChara.put("name","ODBNo");
ProductChara.put("value",CreateOrderReq.getProductOrder().getOrderItem().getProduct().getProductCharacteristic().getODBNO());
ProductCharaArray.put(ProductChara);
produt.put("productCharacteristic",ProductCharaArray);
orderItm.put("product",produt);
orderItemArray.put(orderItm);
productOrder.put("orderItem", orderItemArray);
System.out.println(productOrder.toString());
} catch (JSONException e) {
e.printStackTrace();
}
Related
How I can get the "fields" objects 0,1,2,3,4 & only the "name" object string of every object using JSONOBJECT
[
{
"name": "Bank1",
"fields": {
"0": {
"name": "Email",
"slug": "email",
"type": "input"
},
"1": {
"name": "City",
"slug": "city",
"type": "input"
},
"2": {
"name": "Screenshot",
"slug": "screenshot",
"type": "file"
},
"3": {
"name": "Full Name",
"slug": "full-name",
"type": "input"
}
},
"status": "Active"
},
{
"name": "Bank2",
"fields": {
"0": {
"name": "Email",
"slug": "email",
"type": "input"
},
"1": {
"name": "City",
"slug": "city",
"type": "input"
},
"2": {
"name": "Screenshot",
"slug": "screenshot",
"type": "file"
},
"4": {
"name": "Submitted Date",
"slug": "submitted-date",
"type": "calendar"
}
},
"status": "Active"
}
]
& this is what I try to done
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");
JSONObject jo = jsonObject.getJSONObject("fields");
String j1 = jo.getString("0");
if (!j1.isEmpty()){
JSONObject jo1 = jo.getJSONObject("0");
String f_name1 = jo1.getString("name");
Log.d("Field1.", f_name1);
}
}}catch block...
but the problem is, it gives me value of the object null like [value 4 is null] cuz there is no object for 4 in the first object of fields. please help me solve this prob, appreciate your answers thankyou :)
You can use keys() iterator of json object & loop on it using while (keys.hasNext())
For your example, it would look something like this:
private void parseJson(String response) {
try {
JSONArray jsonArray = new JSONArray(response);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
JSONObject jo = jsonObject.getJSONObject("fields");
Iterator<String> keys = jo.keys();
while (keys.hasNext()) {
String key = keys.next();
JSONObject jo1 = jo.getJSONObject(key);
String f_name1 = jo1.getString("name");
Log.d("Field1.", f_name1);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
There are some problems with get all keys properly in my IDE/JDK11, so I decided to loop over an ArrayList, basing on #MayurGajra solution, ex:
private static List<List<String>> parseJson(String response) throws JSONException {
JSONArray jsonArray = new JSONArray(response);
List<List<String>> result = new ArrayList<>();
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
JSONObject jo = jsonObject.getJSONObject("fields");
List<Object> list = new ArrayList<>();
jo.keys().forEachRemaining(list::add);
List<String> subList = new ArrayList<>();
for (Object o : list) {
String key;
if (isString(o))
key = (String) o;
else
continue;
JSONObject jo1 = jo.getJSONObject(key);
String f_name1 = jo1.getString("name");
subList.add(f_name1);
}
result.add(subList);
}
return result;
}
private static boolean isString(Object o) {
try {
String result = (String) o;
} catch (ClassCastException e) {
return false;
}
return true;
}
The result obtained after processing the above json is as follows:
[[Email, City, Screenshot, Full Name], [Email, City, Screenshot, Submitted Date]]
but it have not to be a List of Lists ;)
-- edit --
To get only first list of elements labeled "name":
try {
System.out.println(parseJson(yourJsonAsString).get(0).toString());
} catch (JSONException e) {
System.out.println("JSONException:" + e.getMessage());
}
The result of above is:
[Email, City, Screenshot, Full Name]
I need to parse a string that contains data of JSON file into a JSONObject and iterate over it's content to get it's keys and values for further treatement after. I'am stuck at parsing the content of a file after transforming it to a string. I tried to user parse() , quote() but it seems i'am missing a detail and i'am making a major mistake.
This is a snippet of the json file i treat :
{
{
"id":0,
"name": "project1",
"couverage": "100",
"completness": "44.8",
"consistency": "46",
}
{
"id":1,
"name": "project2",
"couverage": "100",
"completness": "44.8",
"consistency": "46",
}
{
"id":2,
"name": "project3",
"couverage": "100",
"completness": "44.8",
"consistency": "46",
}
}
and this is the code i developed
public void readfromJsonFile(File jsonFile, long readTimeStamp) {
logger.info("Read from JSON file: {}", jsonFile.getName());
try{
//Read File Content
String content = new String(Files.readAllBytes(jsonFile.toPath()));
JSONParser jsonParser = new JSONParser(content);
JSONObject obj = (JSONObject) jsonParser.parse();
JSONArray key = obj.names();
for (int i = 0; i < key.length (); ++i) {
String keys = key.getString(i);
System.out.println(keys);
String value = obj.getString (keys);
System.out.println(value);
}catch (Exception e) {
logger.error("Failed to parse JSON File: {}", jsonFile.getName());
}
}
You can use Jackson Databind as well.
Create a POJO class. For example :
public class POJO {
private int id;
private String name;
private String couverage;
private String completness;
private String consistency;
// getters, setters and constructors
}
Modify the JSON in the file.
[
{
"id":0,
"name": "project1",
"couverage": "100",
"completness": "44.8",
"consistency": "46"
},
{
"id":1,
"name": "project2",
"couverage": "100",
"completness": "44.8",
"consistency": "46"
},
{
"id":2,
"name": "project3",
"couverage": "100",
"completness": "44.8",
"consistency": "46"
}
]
Code :
public void readfromJsonFile(File jsonFile, long readTimeStamp) {
logger.info("Read from JSON file: {}", jsonFile.getName());
try {
ObjectMapper objectMapper = new ObjectMapper();
POJO[] pojos = objectMapper.readValue(jsonFile, POJO[].class);
for (int i = 0; i < pojos.length; ++i) {
System.out.println(pojos[i].getId());
}
} catch (Exception e) {
logger.error("Failed to parse JSON File: {}", jsonFile.getName());
}
}
Try it like this
JSONArray array_= new JSONArray(content);
JSONObject obj = (JSONObject) array_.get(0);// or any index
then you can use the Object.
I'm having trouble trying to access certain values in a JSON file.
The file has multiple objects stored inside an array.
The value I need to return is "60" inside the "maxspeed" string.
When the current code is executed in debug it just remains in a loop.*Not sure why)
The value of the "result" string is the entire json file.
Would anyone be able to explain how to access this value?
Thanks.
JSON:
{
"version": 0.6,
"generator": "Overpass API",
"osm3s": {
"timestamp_osm_base": "2015-03-16T00:27:03Z",
"copyright": "The data included in this document is from www.openstreetmap.org. The data is made available under ODbL."
},
"elements": [
{
"type": "node",
"id": 768053039,
"lat": 54.9526671,
"lon": -7.7273348
},
{
"type": "node",
"id": 768053040,
"lat": 54.9498094,
"lon": -7.7176056
},
{
"type": "node",
"id": 768053041,
"lat": 54.9497066,
"lon": -7.7173174
},
{
"type": "node",
"id": 768053043,
"lat": 54.9495658,
"lon": -7.7170937
},
{
"type": "node",
"id": 768053044,
"lat": 54.9495035,
"lon": -7.7169816
},
{
"type": "node",
"id": 791492493,
"lat": 54.9494183,
"lon": -7.7168205
},
{
"type": "node",
"id": 795319854,
"lat": 54.9510427,
"lon": -7.7218262
},
{
"type": "node",
"id": 795320324,
"lat": 54.9509153,
"lon": -7.7213706
},
{
"type": "node",
"id": 1922546572,
"lat": 54.9502165,
"lon": -7.7190169
},
{
"type": "node",
"id": 1922546679,
"lat": 54.9504739,
"lon": -7.7199078
},
{
"type": "node",
"id": 1922546692,
"lat": 54.9500860,
"lon": -7.7185174
},
{
"type": "node",
"id": 1922602861,
"lat": 54.9517250,
"lon": -7.7241644
},
{
"type": "node",
"id": 1922622063,
"lat": 54.9514357,
"lon": -7.7231690
},
{
"type": "node",
"id": 2673934802,
"lat": 54.9498543,
"lon": -7.7177617
},
{
"type": "way",
"id": 64273241,
"nodes": [
768053039,
1922602861,
1922622063,
795319854,
795320324
],
"tags": {
"highway": "secondary",
"maxspeed": "60",
"name": "Port Road",
"oneway": "no",
"ref": "R229"
}
},
{
"type": "way",
"id": 64887990,
"nodes": [
795320324,
1922546679,
1922546572,
1922546692,
2673934802,
768053040,
768053041,
768053043,
768053044,
791492493
],
"tags": {
"highway": "secondary",
"maxspeed": "60",
"name": "Port Road",
"oneway": "no",
"ref": "R229"
}
}
]
}
Code:
protected Void doInBackground(String... params) {
android.os.Debug.waitForDebugger();
//String url_select = "http://yoururlhere.com";
StringBuilder builder = new StringBuilder();
HttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(encode2);
try {
HttpResponse response = client.execute(httpGet);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode == 200) {
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(content));
String line;
while ((line = reader.readLine()) != null) {
builder.append(line); } }
else {
Log.e("==>", "Failed to download file"); }
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace(); }
result = builder.toString();
return null;
} // protected Void doInBackground(String... params)
protected void onPostExecute(Void v) {
//parse JSON data
try {
JSONObject parentObject = new JSONObject(result);
JSONArray speedJSON = parentObject.getJSONArray("elements");
JSONObject maxspeed = parentObject.getJSONObject("maxspeed");
System.out.print(""+maxspeed.toString()+"\n");
//String[] elementNames = JSONObject.(speedJSON);
System.out.printf("%d ELEMENTS IN CURRENT OBJECT:\n", speedJSON.length());
for (int i = 0; i< speedJSON.length(); i++)
{
String value = speedJSON.getString(i);
System.out.printf("name=%s, value=%s\n", speedJSON.get(i), value);
}
//And then read attributes like
/* for(int i = 0; i<speedJSON.length(); i++){
JSONObject child = speedJSON.getJSONObject(i);
if(child.getString("type").equals("way")){
JSONObject tag = speedJSON.getJSONObject(i);
JSONObject maxspeed = tag.getJSONObject("tags");
String speed = maxspeed.getString("maxspeed");
txtSpeed.setText(speed);
}
}*/
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
/* try {
JSONArray jArray = new JSONArray(result);
for(int i=0; i < jArray.length(); i++) {
JSONObject jObject = jArray.getJSONObject(i);
String speedLimit = jObject.getString("maxspeed");
txtSpeed.setText(speedLimit);
} // End Loop
this.progressDialog.dismiss();
} catch (JSONException e) {
Log.e("JSONException", "Error: " + e.toString());
} // catch (JSONException e)
*/ } // protected void onPostExecute(Void v)
}
Okay your first problem is that not all JSONObjects from your "elements" array have a max speed property. The second problem is that you are not iterating over your JSONArray correctly.
Lets start with the second proble:
for (int i = 0; i < speedJSON.length(); i++) {
JSONObject element = (JSONObject) speedJSON.get(i);
}
Now your element is the JSONObject which contains your different properties (type, id, lon, ...)
To solve your first problem you can check if a JSONObject contains the key you are looking for (maxspeed)
if (!element.isNull("tags") {
JSONObject tags = (JSONObject)element.get("tags");
if (!tags.isNull("maxspeed") {
String maxspeed = tags.getString("maxspeed");
}
} else {
//Your error handling here...
}
Hope this helps!
I need to parse a JSON file and put the data into a HTML table. I am using GWT for this application, the data shall be read from the file on the server side and passed to the client on page load.
The format for the JSONObjects in the file are as follows:
{
"Object 1": [
{ "value1": [ "subKey1", "subValue2" ], "value2": "val", "value3": { "key1": val1, "key2": val2, "key3": val3} },
{ "value2": [ "subKey1", "subValue2" ], "value2": "val", "value3": { "key1": val1, "key2": val2, "key3": val3} },
....
....
],
"Object 2": [
{ "value1": [ "subKey1", "subValue2" ], "value2": "val", "value3": { "key1": val1, "key2": val2, "key3": val3} },
{ "value2": [ "subKey1", "subValue2" ], "value2": "val", "value3": { "key1": val1, "key2": val2, "key3": val3} },
....
....
],
....
}
Up until now, I have only done simple JSON parsing. The problem I am having here is that the data I am working with has a unique name for each object so I cannot seem to parse them into an array of JSONObjects.
I have attempted to parse them (using JSON simple) this way but I am throwing an error.
try {
JSONParser parser = new JSONParser();
JSONObject obj;
obj = (JSONObject) parser.parse(new FileReader("file.json"));
JSONArray array = new JSONArray();
array.add(obj.get("Object1"));
array.add(obj.get("Object2"));
array.add(obj.get("Object3"));
array.add(obj.get("Object4"));
JSONObject jo;
for (Object o : array) {
jo = (JSONObject) o;
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
}
But this throws an error:
org.json.simple.JSONArray cannot be cast to org.json.simple.JSONObject
Another method from my understanding is to create a POJO class for the objects but since each JSONObject has a different identifier, does that mean each object must have its own unique class? Some JSON2Java methods I have used just create a new class for each of them.
You can check the instance of the Object before casting it:
for (Object obj : array) {
if (obj instanceof JSONArray) {
// It's an array
yourJsonArray = (JSONArray)obj;
} else if (obj instanceof JSONObject) {
// It's an object
yourJsonObject = (JSONObject)obj;
} else {
// It's string, number...
}
}
I am stuck here and would like to extract using java the second link of the facebook query below
{
"data": [
{
"attachment": {
"media": [
{
"photo": {
"images": [
{
"src": "https://fbcdn-photos-h-a.akamaihd.net/hphotos-ak-prn2/1508634_699393523428883_996610253_s.png"
},
{
"src": "https://fbcdn-sphotos-h-a.akamaihd.net/hphotos-ak-prn2/s720x720/1508634_699393523428883_996610253_n.png"
}
]
}
}
]
}
}
]
}
my code below, is obviously not working
try
{
List<JsonObject> queryResults = facebookClient.executeFqlQuery(query, JsonObject.class);
if(!queryResults.isEmpty())
{
JsonObject facebookPosturl_J = queryResults.get(0);
facebook_post = facebookPosturl_J.getString("src");
}
}
catch (Exception e){logger.warn("Unexpected error", e);}
Try calling:
facebookPosturl_J.getJsonArray("data").getJsonObject(0).getJsonObject("attachment").getJsonArray("media").getJsonObject(0).getJsonObject("photo").getJsonArray("images").getJsonObject(1).getString("src")