How do you store arrays into a JSON object? - java

I have a the following objects:
server: a string
products: will be arrays within the server
productProperties: will be an array within a product
Is the following a correct way to store the value in a JSON format?
JSONOBJECT jmap = new JSONOBJECT();
jsonArray jproduct = new jsonArray ();
jsonArray jproductsProperty1 = new jsonArray ();
jproductsProperty1 .put("P1");
jproductsProperty1 .put("P2");
jsonArray jproductsProperty2 = new jsonArray ();
jproductsProperty2 .put("Q1");
jproductsProperty2 .put("Q2");
jproduct.put(jproductsProperty1);
jproduct.put(jproductsProperty2);
jmap.put(server,jproduct);
out.print(jmap.toString());

first argument its just a key and second its your object could be a collection like a array
JSONOBJECT jmap = new JSONOBJECT();
jsonArray jproductsProperty1 = new jsonArray ();
jproductsProperty1.put("P1");
jproductsProperty1.put("P2");
jsonArray jproductsProperty2 = new jsonArray ();
jproductsProperty2.put("Q1");
jproductsProperty2.put("Q2");
jmap.put("jproductsProperty1", jproductsProperty1 );
jmap.put("jproductsProperty2", jproductsProperty2 );

okay i think i need to use two maps here .....like this
JSONObject jmap1 = new JSONObject();
JSONObject jmap2 = new JSONObject();
JSONArray jproduct = new JSONArray();
JSONArray jproductsProperty1 = new JSONArray();
jproductsProperty1 .put("P1");
jproductsProperty1 .put("P2");
JSONArray jproductsProperty2 = new JSONArray();
jproductsProperty2 .put("Q1");
jproductsProperty2 .put("Q2");
jproduct.put(jproductsProperty1);
jproduct.put(jproductsProperty2);
jmap2.put("jproductsProperty1", jproductsProperty1 );
jmap2.put("jproductsProperty2", jproductsProperty2 );
jmap1.put("A",jmap2);
System.out.println(jmap1);

Related

How to build a JSONObject with a JSONArray?

im kinda new using JSON, and everything was fine until i have to make this JSON format.
"function":"ListarHoteles",
"parameters":[""]
Right now my code:
JSONObject JSONarr = new JSONObject();
JSONArray pam = new JSONArray();
jo.put("function", "ListarHoteles");
pam.add(" ");
JSONObject mainOBJ = new JSONObject();
mainOBJ.put("parameters", pam);
And im receiving:
{"{\"function\":\"ListarHoteles\"}":{},"parameters":[" "]}
Thank you
Is this what you want?
JSONObject jsonObject = new JSONObject();
jsonObject.put("function", "ListarHoteles");
JSONArray arr = new JSONArray();
arr.add("");
jsonObject.put("parameters", arr);
System.out.println(jsonObject.toString(2));
Output:
{
"function":"ListarHoteles",
"parameters":[
""
]
}

Parse Json array in android / java file

I am facing a problem to reach to an object which is inside an array of another object of another array. To make it simpler i am attaching the image (attached below), basically i want to reach to json object "0" inside jsonarray ticket itmes.
my codes are
JSONArray jsonArray = new JSONArray(buffer.toString());
JSONObject jsonobject = null;
jsonobject = jsonArray.getJSONObject(0);
JSONArray jsonarray1 = new JSONArray(buffer.toString());
jsonarray1 = jsonobject.getJSONArray("ticketitems");
JSONObject jsonobject1 = null;
TicketItem ticketItemList = new TicketItem();
jsonobject1 = jsonArray.getJSONObject(0);
ticketItemList.setItemCount(jsonobject1.getInt("itemCount"));
TicketItemList.add(ticketItemList);
However, jsonarray1 generates an exception stating
org.json.JSONException: No value for ticketitems
enter image description here
replace
jsonarray1 = jsonobject.getJSONArray("ticketitems");
with
jsonarray1 = jsonobject.getJSONArray("ticketItems");
It's case sensitive. It should be
jsonarray1 = jsonobject.getJSONArray("ticketItems");

Convert Java Map in to net.sf.json.JSONArray.JSONArray()

How to convert Java Map into net.sf.json.JSONArray.JSONArray()?
Map<String, String> linkedHMapDropDownList = new LinkedHashMap<String, String>();
linkedHMapDropDownList.put("X", "XXX");
linkedHMapDropDownList.put("Y", "YYY");
linkedHMapDropDownList.put("Z", "ZZZ");
I am looking something like
JSONArray array= new JSONArray(linkedHMapDropDownList);
Found the way to convert, thought might be useful for others
JSONObject jsonObj = new JSONObject();
jsonObj.accumulateAll(linkedHMapDropDownList);
JSONArray jsonArray = new JSONArray();
jsonArray.add(jsonObj);

Generating a JSON array

I need to generate a JSON array object ("MainData") as shown below using Java. Can any one suggest to me how can be this done?
{
"MainData":{
"columnHeaderKeys":null,
"rowHeaders":[
{
"id":0001,
"name":abcd
},
{
"id":0002,
"name":xyz
}
],
"data":[
{
"id":0001,
"rowId":"R1",
"status":PASSED
},
{
"id":0002,
"rowId":"R2",
"status":PASSED
}
]
}
}
Using Google GSON, it's quite simple:
JSONObject result = new JSONObject();
result.put("columnHeadersKeys", JSONObject.NULL);
JSONArray headers = new JSONArray();
JSONObject obj = new JSONObject();
obj.put("id", 1);
obj.put("name", "abcd");
headers.put(obj);
obj = new JSONObject();
obj.put("id", 2);
obj.put("name", "xyz");
headers.put(obj);
result.put("rowHeaders", headers);
JSONArray data = new JSONArray();
obj = new JSONObject();
obj.put("id", 1);
obj.put("rowId", "R1");
obj.put("status", "PASSED");
data.put(obj);
obj = new JSONObject();
obj.put("id", 2);
obj.put("rowId", "R2");
obj.put("status", "PASSED");
data.put(obj);
result.put("data", data);
String output = result.toString();
Note that the entire creation of the object can be chained in one statement - however I find it easier to read when it's split out.
Use the Jackson library.
A sample code from the tutorial:
ObjectMapper mapper = new ObjectMapper();
Map<String,Object> userData = new HashMap<String,Object>();
Map<String,String> nameStruct = new HashMap<String,String>();
nameStruct.put("first", "Joe");
nameStruct.put("last", "Sixpack");
userData.put("name", nameStruct);
userData.put("gender", "MALE");
userData.put("verified", Boolean.FALSE);
userData.put("userImage", "Rm9vYmFyIQ==");
mapper.writeValue(new File("user-modified.json"), userData);
You can do like this It works perfectly for me with this line
Log.i("MainJSON", MainJSON.toString()); I have printed Created JSONObject
try{
JSONObject jo1=new JSONObject();
jo1.put("id",001);
jo1.put("name","abcd");
JSONObject jo2=new JSONObject();
jo2.put("id",002);
jo2.put("name","xyz");
JSONArray jarr1=new JSONArray();
jarr1.put(0, jo1);
jarr1.put(1, jo2);
JSONObject jo3=new JSONObject();
jo3.put("id",0001);
jo3.put("rowId","R1");
jo3.put("status","PASSED");
JSONObject jo4=new JSONObject();
jo4.put("id",0002);
jo4.put("rowId","R2");
jo4.put("status","PASSED");
JSONArray jarr2=new JSONArray();
jarr2.put(0, jo3);
jarr2.put(1, jo4);
JSONObject MainDataObj=new JSONObject();
MainDataObj.put("rowHeaders", jarr1);
MainDataObj.put("data", jarr2);
MainDataObj.put("columnHeaderKeys", "null");
JSONObject MainJSON=new JSONObject();
MainJSON.put("MainData", MainDataObj);
Log.i("MainJSON", MainJSON.toString());
}catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
Take a look here. You will find many projects that will help you.
I would try JSONObject.java from Crockford's JSON for Java Github repository.
Simple usage :
JSONObject obj = new JSONObject()
.put("MainData", new JSONObject()
.put("columnHeaderKeys", null)
.put("rowHeaders", new JSONArray()
.put(new JSONObject()
.put("id", "001")
.put("name", "abc")
)
.put(new JSONObject()
.put("id", "002")
.put("rowId", "R1")
// ...
)
);
Output string with :
String jsonString = obj.toString();
or write directly to file :
obj.write(new FileWriter(new File("/path/to/destination/file")));

Android ArrayList<String[]> to PHP

I need my app to send an ArrayList<String[]> to php, I have this to call the service:
ArrayList<String[]> Items = new ArrayList<String[]>();
(...)
JSONObject JSONSend= new JSONObject();
JSONSend.put("Items", Items );
HttpConnectionParams.setConnectionTimeout(client.getParams(), 10000);
HttpResponse response;
HttpPost post = new HttpPost(SERVICE);
post.setHeader("json", JSONSend.toString());
StringEntity se = new StringEntity(JSONSend.toString());
se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,"application/json"));
post.setEntity(se);
response = client.execute(post);
and on the PHP service:
$data = file_get_contents('php://input');
$json = json_decode($data);
$Items = $json->{'Items'};
error_log($Items);
and the php is returning this:
[[Ljava.lang.String;#413e2fd0, [Ljava.lang.String;#413a2940, [Ljava.lang.String;#4139df18, [Ljava.lang.String;#4141b5b0, [Ljava.lang.String;#413931c8, [Ljava.lang.String;#41348b40, [Ljava.lang.String;#41393928]
The type of the $ServMade is string, so how can I take care of the data as an array on php? Am I missing something?
Try the following when generating json string in android:
JSONObject JSONSend= new JSONObject();
JSONArray ja = null;
JSONArray tmp = new JSONArray();
for(String s[] : Items){
ja = new JSONArray();
for(int i = 0; i<s.length; i++)
ja.put(s[i]);
tmp.put(ja);
}
JSONSend.put("Items", tmp);
The problem here is that You call .toString() (within Java) on an array of strings (String[]) that while NOT overrided returns exactly what You get in the JSON: [Ljava.lang.String;#413e2fd0].
Don't know exactly the JSONObject but I guess You should transform the ArrayList<String[]> (so the array of arrays of strings) to something different for JSONObject to handle it correctly.
Also, in PHP, You do not have to call $Items = $json->{'Items'}; - it is okay to call $Items = $json->Items;.

Categories