Json array manipulation in android - java

If I have a Json array object that looks like this:
[
{"values here"},
{"values here"},
{"values here"}
]
And I want a Json array object that looks like this:
{
"key1":"value1","key2":"value2","key3":"value3"
:[
{"values here"},
{"values here"},
{"values here"}
]
}
Is it possible for me to insert another json object at the front of all the elements in the array and encloses them.

Use the following Example
JSONObject student1 = new JSONObject();
try {
student1.put("id", "3");
student1.put("name", "NAME OF STUDENT");
student1.put("year", "3rd");
student1.put("curriculum", "Arts");
student1.put("birthday", "5/5/1993");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
JSONObject student2 = new JSONObject();
try {
student2.put("id", "2");
student2.put("name", "NAME OF STUDENT2");
student2.put("year", "4rd");
student2.put("curriculum", "scicence");
student2.put("birthday", "5/5/1993");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
JSONArray jsonArray = new JSONArray();
jsonArray.put(student1);
jsonArray.put(student2);
JSONObject studentsObj = new JSONObject();
studentsObj.put("Students", jsonArray);
String jsonStr = studentsObj.toString();
System.out.println("jsonString: "+jsonStr);
above Example taken from Here

I'm not sure what you mean by "encloses".
You can have the first element of the array be your object.
[
{
"key1": "value1",
"key2": "value2",
"key3": "value3"
},
"values here",
"values here",
"values here"
]
You can also have an object like
{
"first": {
"key1": "value1",
"key2": "value2",
"key3": "value3"
},
"rest": [
"values here",
"values here",
"values here"
]
}

Related

How to save data from textfields to json file?

how to save data from our textfields. For example i want to get this:
[
{
"Patient": {
"name": "John",
"surname": "Cena"
}
},
{
"Patient2": {
"name": "Roger",
"surname": "Federer"
}
}
]
And it was my try:
JSONObject obj = new JSONObject();
obj.put("imie", field1.getText());
obj.put("nazwisko", field2.getText());
try (FileWriter Data = new FileWriter("Data.JSON")) {
Data.write(obj.toJSONString());
Data.write(obj1.toJSONString());
} catch (IOException e1) {
e1.printStackTrace();
}
but i dont get "Patient2" and it overwriting my first patient if i press save button instead of add new one.
You should be using JSONArray to store several JSONObject instances:
// build object
JSONObject obj = new JSONObject();
obj.put("name", field1.getText());
obj.put("surname", field2.getText());
// build "patient"
JSONObject patient = new JSONObject();
patient.put("patient", obj);
// build another object
JSONObject obj1 = new JSONObject();
obj1.put("name", "Roger");
obj1.put("surname", "Federer");
// build another patient
JSONObject patient1 = new JSONObject();
patient1.put("patient1", obj1);
// create array and add both patients
JSONArray arr = new JSONArray();
arr.put(patient);
arr.put(patient1);
try (FileWriter Data = new FileWriter("Data.JSON")) {
Data.write(arr.toString(4)); // setting spaces for indent
} catch (IOException e1) {
e1.printStackTrace();
}
This code produces JSON:
[
{
"patient": {
"surname": "Doe",
"name": "John"
}
},
{
"patient1": {
"surname": "Federer",
"name": "Roger"
}
}
]

Convert Json payload to java objects

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

JSON parser in Java using Map

I'm trying to parse a json file using the org.json.simple library and I'm getting null pointer exception when I try to instantiate the iterator with the Map.
#SuppressWarnings("unchecked")
public static void main(String[] args) {
JSONParser parser = new JSONParser();
try {
Object obj = parser.parse(new FileReader("wadingpools.json"));
JSONObject jsonObject = (JSONObject) obj;
System.out.println(jsonObject);
JSONArray featuresArray = (JSONArray) jsonObject.get("features");
Iterator iter = featuresArray.iterator();
while (iter.hasNext()) {
Map<String, String> propertiesMap = ((Map<String, String>) jsonObject.get("properties"));
Iterator<Map.Entry<String, String>> itrMap = propertiesMap.entrySet().iterator();
while(itrMap.hasNext()){
Map.Entry<String, String> pair = itrMap.next();
System.out.println(pair.getKey() + " : " + pair.getValue());
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
}
}
}
Here is a snippet of part of the JSON file. I'm trying to get the NAME in the properties object.
{
"type": "FeatureCollection",
"crs": {
"type": "name",
"properties": {
"name": "urn:ogc:def:crs:OGC:1.3:CRS84"
}
},
"features": [{
"type": "Feature",
"properties": {
"PARK_ID": 393,
"FACILITYID": 26249,
"NAME": "Wading Pool - Crestview",
"NAME_FR": "Pataugeoire - Crestview",
"ADDRESS": "58 Fieldrow St."
},
At (Map<String, String>) jsonObject.get("properties") you are trying to access properties from your "root" object (held by jsonObject) which doesn't have such key. You probably wanted to get value of that key from object held by features array. You already created iterator for that array, but you never used it to get elements held by it. You need something like
while (iter.hasNext()) {
JSONObject tmpObject = (JSONObject) iter.next();
...
}
and call get("properties") on that tmpObject.

Parsing a complex JSON file

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

JSONObject in Android

Here i want to fetch the data from the json, but i am getting only first two objects value (25, 44) but the ids are 50,60 . I don't know whats wrong with this code.
Below is my response from the server:
{
"product": {
"25": {
"training": "First Name",
"taken": null,
"date": "1386737285",
"body":"http://abc.xyz.in/video1.mp4",
"image": "http://abc.xyz.in/video1.jpg"
},
"44": {
"training": "Second Name",
"taken": null,
"date": "1389951618",
"body":"http://abc.xyz.in/video2.mp4",
"image":"http://abc.xyz.in/video2.jpg"
},
"50": {
"training": "Third Name",
"taken": null,
"date": "1389971004",
"body":"http://abc.xyz.in/video3.mp4",
"image": "http://abc.xyz.in/video3.jpg"
},
"60": {
"training": "Fourth Name",
"taken": null,
"date": "1390003200",
"body": "http://abc.xyz.in/video4.mp4",
"image": "http://abc.xyz.in/video4.jpg"
}
}
}
Here is the code for fetching data from json:
public String[] getDataFromResponse(String jsonProfileResponse,String secondParam,
String attributeName ) {
String[] attributeValue = null;
try {
json = new JSONTokener(jsonProfileResponse).nextValue();
if (json instanceof JSONObject) {
JSONObject jsonObject = (JSONObject) json;
JSONObject jObj = jsonObject.getJSONObject(secondParam);
System.out.println(jObj);
Iterator<?> keys = jObj.keys();
List<String> listitems = new ArrayList<String>();
List<String> nids = new ArrayList<String>();
while (keys.hasNext()) {
nids.add(String.valueOf(keys.next()));
JSONObject jsonObj = jObj.getJSONObject(String.valueOf(keys
.next()));
System.out.println(jsonObj);
listitems.add(jsonObj.getString(attributeName));
}
attributeValue = listitems.toArray(new String[0]);
trainingId = nids.toArray(new String[0]);
}
} catch (JSONException ex) {
ex.printStackTrace();
}
return attributeValue;
}
Thanks for the considering...
Inside the hasNext you call twice keys.next()
So, instead of
nids.add(String.valueOf(keys.next()));
JSONObject jsonObj = jObj.getJSONObject(String.valueOf(keys.next()));
you have to do
String currentKey = String.valueOf(keys.next());
nids.add(currentKey);
JSONObject jsonObj = jObj.getJSONObject(currentKey);
String key="";
while (keys.hasNext()) {
key= keys.next()
JSONObject jsonObj = jObj.getJSONObject(String.valueOf(key));
nids.add(key));
System.out.println(jsonObj);
listitems.add(jsonObj.getString(attributeName));
}
use of key.next() twice is problem
because in JSONObject, the order of the keys is undefined.
#see: http://developer.android.com/reference/org/json/JSONObject.html#keys%28%29
try to sort your data on server, then response it in JSONArray

Categories