Create an array of JSON Objects - android

I need to create a JSON Object for an Arraylist. Below is the code
public boolean submitOrder(ArrayList<OrderDetailsData> orderList) {
serUri = "lists.json";
method = "post";
JSONObject jsonObject = new JSONObject();
JSONObject json = new JSONObject();
JSONArray array = new JSONArray();
try {
for (int i = 0; i < orderList.size(); i++) {
json.put("orderno", orderList.get(i).getOrderNumber()
.toString());
json.put("tableno", orderList.get(i).getTableNumber()
.toString());
json.put("itemname", orderList.get(i).getItemName().toString());
json.put("amount", orderList.get(i).getAmount().toString());
json.put("ordstatus", orderList.get(i).getOrderStatus()
.toString());
array.put(json);
}
catch (JSONException je) {
return false;
}
try {
jsonObject.put("list", array);
} catch (JSONException je) {
return false;
}
WebServiceAsyncTask webServiceTask = new WebServiceAsyncTask();
webServiceTask.execute(serUri, method,jsonObject, this);
return true;
}
The problem is its creating object with details of last row item at each position. Say if my orderList has 3 rows, the jsonObject created has 3 rows but with 3rd row data in all 3. Seems like its overriding data for all the rows with latest row fetched. I tried with couple of other ways but still not getting desired result. Please advise. Thanks.
JSON Object created:
{"list":[{"amount":"10.50","orderno":"0220130826163623","quantity":"1","itemname":"Pollo Al Horno","tableno":"02","ordstatus":"placed"},{"amount":"10.50","orderno":"0220130826163623","itemname":"Pollo Al Horno","tableno":"02","ordstatus":"placed"},{"amount":"10.50","orderno":"0220130826163623","itemname":"Pollo Al Horno","tableno":"02","ordstatus":"placed"},{"amount":"10.50","orderno":"0220130826163623","itemname":"Pollo Al Horno","tableno":"02","ordstatus":"placed"},{"amount":"10.50","orderno":"0220130826163623","itemname":"Pollo Al Horno","tableno":"02","ordstatus":"placed"},{"amount":"10.50","orderno":"0220130826163623","itemname":"Pollo Al Horno","tableno":"02","ordstatus":"placed"},{"amount":"10.50","orderno":"0220130826163623","itemname":"Pollo Al Horno","tableno":"02","ordstatus":"placed"},{"amount":"10.50","orderno":"0220130826163623","itemname":"Pollo Al Horno","tableno":"02","ordstatus":"placed"}]}
The above object has only last item in each row.

Your JSONObject json = new JSONObject(); should be within the loop.
Additionally, you should not do a get(i) each time to access properties (for performance). You can use the other construct of the for loop:
for (OrderDetailsData data : orderList) {
JSONObject json = new JSONObject();
json.put("orderno", data.getOrderNumber().toString());
// ...
}
Finally, maybe you should consider having a function that reads/writes a JSON object from an OrderDetailsData so that you can reuse the code in other webservices.

Small mistake
try {
for (int i = 0; i < orderList.size(); i++) {
JSONObject json = new JSONObject(); // update here
json.put("orderno", orderList.get(i).getOrderNumber()
.toString());
json.put("tableno", orderList.get(i).getTableNumber()
.toString());
json.put("itemname", orderList.get(i).getItemName().toString());
json.put("amount", orderList.get(i).getAmount().toString());
json.put("ordstatus", orderList.get(i).getOrderStatus()
.toString());
array.put(json);
}
catch (JSONException je) {
return false;
}

Look at this I'm trying to use GSON lib, try out this, I'm not tested. This should work fine.
From Json string to Json object this way:
String jsonStr = "{\"a\": \"A\"}";
Gson gson = new Gson();
JsonElement element = gson.fromJson (jsonStr, JsonElement.class);
JsonObject jsonObj = element.getAsJsonObject();
For your code this should work fine:
public boolean submitOrder(ArrayList<OrderDetailsData> orderList)
{
serUri = "lists.json";
method = "post";
Gson gson = new Gson();
String jsonstr = new Gson().toJson(orderList);
JsonElement element = gson.fromJson (jsonStr, JsonElement.class);
JsonObject jsonObject = element.getAsJsonObject();
WebServiceAsyncTask webServiceTask = new WebServiceAsyncTask();
webServiceTask.execute(serUri, method,jsonObject, this);
return true;
}

This following snippet will create array of json objects in single statement, it even performs null checks while creating json from object using Google's Gson library.
public boolean submitOrder(ArrayList<OrderDetailsData> orderList) {
Gson gson = new Gson();
JsonObject myObj = new JsonObject();
JsonElement ordersObj = gson.toJsonTree(orderList);
myObj.add("list", ordersObj);
}

You need to instantiate the json object inside the for loop.

Related

Read Json in android

{"721xxxxxxx":true,"722xxxxxxx":true,"723xxxxxxx":true}
How can i read all the keys in the json and how can count all the data in the Jsonarray
My code-->
String members = s;
/* s contain {"721xxxxxxx":true,"722xxxxxxx":true,"723xxxxxxx":true} */
JSONArray jsonChildArr = new JSONArray(members);
Log.e("Error","Data in jsonArray--->"+jsonChildArr.length());
Simple Way to Read JSON Object
JSONObject jsonObject = new JSONObject(members);
Log.i("Data","Data in jsonObject--->"+jsonObject.getBoolean("721xxxxxxx"));
Do Like this.
try {
String members = s;
/* s contain {"721xxxxxxx":true,"722xxxxxxx":true,"723xxxxxxx":true} */
JSONObject obj = new JSONObject(members);
JSONArray array = obj.names();
Log.d("ItemCount",array.length()+"");
for(int i=0;i<array.length();i++){
Log.d("Item",array.getString(i)+":"+ obj.getBoolean(array.getString(i));
}
} catch (JSONException e) {
e.printStackTrace();
}
Try this,
JSONObject jsonObject = new JSONObject(result);
boolean data = jsonObject .getBoolean("721xxxxxxx");
Log.d("Data","data:"+data );
try this:
String jsonStr = "{"721xxxxxxx":true,"722xxxxxxx":true,"723xxxxxxx":true}";
JSONObject itemJsonObj = new JSONObject(jsonStr );
HashMap<String,Boolean> result = new HashMap<>();
while(itemJsonObj.keys().hasNext()){
//parse json and save as key-value.
result.put(itemJsonObj.keys().next()+"",itemJsonObj.get(itemJsonObj.keys().next());
// result.size() is like array's size.
}
I wrote a library for parsing and generating JSON in Android http://github.com/amirdew/JSON
for your sample:
JSON jsonData = new JSON(jsonString);
int count = jsonData.count();

How to convert JSONObject to JSONArray in Android?

I have request something like this.
{"REQ_DATA":
{"CLPH_NO":"010123456789","USE_INTT_NO":""}
}
but server accepts only this
{"REQ_DATA":
[{"CLPH_NO":"010123456789","USE_INTT_NO":""}]
}
What should I do? I quite noob about JSON, please help me.
REQ_DATA needs to be a JSONArray. Try implementing something like this
try {
JSONObject object = new JSONObject();
JSONArray requiredDataArray = new JSONArray();
JSONObject data = new JSONObject();
data.put("CLPH_NO", "010123456789");
data.put("USE_INTT_NO", "");
requiredDataArray.put(data);
object.put("REQ_DATA", requiredDataArray);
Log.d("JSON", object.toString());
} catch (JSONException e) {
e.printStackTrace();
}
You can try:
JSONObject fromRequest = request.getJSONObject();// given from request
JSONObject toServer = new JSONObject();
JSONArray arr = new JSONArray();
arr.put(fromRequest.get("REQ_DATA"));
toServer.put("REQ_DATA", arr);
Jsonarray array = new Jsonarray();
Jsonobject insidearray = new jsonobject;
insidearray.put("CLPH_NO", "010123456789");
insidearray.put("USE_INTT_NO", "");
array.put(insidearray);
Jsonobject object = new Jsonobject();
object.put("REQ_DATA",array);
The variables may need a little editing, doing this from a phone but there you go
You don't change a JSONObject to a JSONArray, rather, you create a JSONArray and then add the JSONObject to that array.
try {
JSONObject reqData = new JSONObject();
reqData.put("CLPH_NO", "010123456789");
reqData.put("USE_INTT_NO", "");
JSONArray array = new JSONArray();
array.put(reqData);
JSONObject request = new JSONObject();
request.put("REQ_DATA", reqData);
String requestAsJSONString = request.toString();
// call web service
} catch (JSONException e) {
// handle exception
}
You need to send requestAsJSONString to the server.
Furthermore, I suggest you put the JSON object keys in final fields, like so:
static final String KEY_REQ_DATA = "REQ_DATA";
and then use KEY_REQ_DATA in your code instead of using the hardcoded String.
This is simple solution for your json string as per server check it
JSONObject jo = new JSONObject();
try {
jo.put("CLPH_NO", "010123456789");
jo.put("USE_INTT_NO", "");
} catch (Exception e) {
}
JSONArray ja = new JSONArray();
ja.put(jo);
JSONObject final_jo = new JSONObject();
try {
final_jo.put("REQ_DATA", ja);
} catch (Exception e) {
}
Toast.makeText(getApplicationContext(),final_jo.toString(),Toast.LENGTH_LONG).show();
Just simple solution without using any hard-coded Strings
JSONObject currentJson = new JSONObject(yourJsonString); //Your current jsonObject
JSONObject newJsonObject = new JSONObject(); //new jsonObject you want to send to server
newJsonObject.put(currentJson.keys().next().toString(),
new JSONArray().put(currentJson.getString(currentJson.keys().next().toString())));

How to create JSONObject and JSON ARRAy from json string in android?

My String contains json
result=[{"USER_ID":83,"PROJECT_BY_DETAILS":"An adaptation of a nursery rhyme into a dramatic film"},{"USER_ID":88,"PROJECT_BY_DETAILS":"Test - over ye mountain blue "}]
How to create JSONOBject and JSONarray from this string
I used this code
JSONObject json =new JSONObject(result);
//Get the element that holds the earthquakes ( JSONArray )
JSONArray earthquakes = json.getJSONArray("");
i got error
Error parsing data org.json.JSONException: Value [{"USER_ID":83,"PRO
If it starts with [ its an array, try with:
JSONArray json =new JSONArray(result);
Difference between JSONObject and JSONArray
use this code for your JsonArray:
try {
JSONArray json = new JSONArray(YOUR_JSON_STRING);
for (int i = 0; i < json.length(); i++) {
JSONObject jsonDATA = json.getJSONObject(i);
String jsonid = jsonDATA.getInt("USER_ID");
String jsondetails = jsonDATA.getString("PROJECT_BY_DETAILS");
}
} catch (JSONException e) {
return null;
}
use Gson for you to do that.
That Json response is an array you know it because of the square brackets [].
Create a mapping object (a java class) with field USER_ID and PROJECT_BY_DETAILS.
public class yourClass(){
public String USER_ID;
public String PROJECT_BY_DETAILS;
}
Create a Type array like so.
final Type typeYourObject = new TypeToken>(){}.getType();
define your list private
List yourList;
Using Gson you will convert that array to a List like so
yourList = gson.fromJson(yourJson, typeYourObject);
with that list later you can do whatever you want. Also with Gson convert it back to JsonArray or create a customs JsonObject.
According to my understanding the JSON object looks like this,
{
"RESULT":[
{
"USER_ID":83,
"PROJECT_BY_DETAILS":"An adaptation of a nursery rhyme into a dramatic film"
},
{
"USER_ID":88,
"PROJECT_BY_DETAILS":"Test - over ye mountain blue "
}
]
}
You are converting this to a String and you wish to re-construct the JSON object. The decode function in the android-side would be this,
void jsonDecode(String jsonResponse)
{
try
{
JSONObject jsonRootObject = new JSONObject(jsonResponse);
JSONArray jData = jsonRootObject.getJSONArray("RESULT");
for(int i = 0; i < jData.length(); ++i)
{
JSONObject jObj = jData.getJSONObject(i);
String userID = jObj.optString("USER_ID");
String projectDetails = jObj.optString("PROJECT_BY_DETAILS");
Toast.makeText(context, userID + " -- " + projectDetails,0).show();
}
}
catch(JSONException e)
{
e.printStackTrace();
}
}

Unable to get the JSON data from the JSONObject in android?

Currently, I'm having a minor trouble trying to get the string data from the jsonArray, however, I'm unable to get the value . I've got the data in the json object Example:
{
"lot":[
{
"id":"271",
"lot_date":"2015-05-25"
}
],
"numb3":[
{
"id":"675",
"lot_date":"2015-05-25"
}
],
"num4":[
{
"id":"676",
"lot_date":"2015-05-25"
}
],
"result":"OK"
}
The data above is stored in the JsonObject jsonobj. And what I want to do is to check if the JSON array JSONArray lot6 = jsonobj.optJSONArray("lot6"); contains the values or not , and if it's not null get the string data. However, even the data contains in the lot6 array, the result is null.
JSONArray lot6 = jsonobject.optJSONArray("lot6");
Log.d("LOT6",lot6+"");
if (lot6 != null) {
jsonarry2 = jsonobject.getJSONArray("lot6");
//3.if not null get the string data from the
for (int i = 0; i < jsonarry2.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
jsonobject = jsonarry2.getJSONObject(i);
ListData worldpop = new ListData();
worldpop.set_date(jsonobject.optString("lot_date"));
worldpop.set__id(jsonobject.optString("id"));
world.add(worldpop);
}
//5. test this part of the variable
String lotdate = world.get(0).get_date();
String lotid = world.get(0).get__id();
Hi please check Not lot6 its lot. please folloe below formate to get out out.
String s="{\"lot\":[{\"id\":\"271\",\"lot_date\":\"2015-05-25\"}],\"numb3\":[{\"id\":\"675\",\"lot_date\":\"2015-05-25\"}],\"num4\":[{\"id\":\"676\",\"lot_date\":\"2015-05-25\"}],\"result\":\"OK\"} ";
try{
JSONParser parser = new JSONParser();
JSONObject json = (JSONObject) parser.parse(s);
String arr[]={"lot","numb3","num4"};
for(int i=0;i<json.size()-1;i++){
JSONArray ja=(JSONArray)json.get(arr[i]);
for(int j=0;j<ja.size();j++){
JSONObject jo1=(JSONObject) ja.get(j);
System.out.println("lot_date: "+jo1.get("lot_date")+" Id "+jo1.get("id"));
}
// System.out.println(ja);
}
System.out.println(json.get("result"));
}catch (Exception e) {
System.out.println(e);
}

Save json to array key-value in android

I have a problem with json.
I get this response from server:
{"TESTS":true,"TESTS_VIEW":true,"ORDER":true,"PARAMETERS":true,"VIEW":true}
How can I save this data in array or something else to have schema: key - value?
Hmm, not sure I understand why you want this. A JSONObject gives you exactly that, have a look at JSONObject.get():
JSONObject json = new JSONObject(yourjsonstringfromserver);
boolean tests = json.getBoolean("TESTS");
Still, if you want to iterate over all values you can do like this:
Map<String, Object> map = new HashMap<String, Object>();
Iterator<String> keys = json.keys();
for(String key : keys) {
try {
Object value = json.get(key);
map.put(key, value);
}
catch (JSONException e) {
// Something went wrong!
}
}
JSONObject object = YourObjectHere;
Map<String,Boolean> dict = new HashMap<String,Boolean>();
Iterator it = object.keyes();
while( it.hasNext() ){
String key = it.next();
String value = object.get(key);
dict.put( key, value );
}
Solution, more or less. //Written without checking in IDE so may contain bugs/errors
JSONObject json = new JSONObject(response);
json.getInt(keyA);
json.getString(keyB);
and etc;
You can using this function with httpResponse is your json string:
public static YourModel parseJson(String httpResponse) {
YourModel objObject = new YourModel();
try {
JSONArray jsonArrayData = new JSONArray(httpResponse);
if (jsonArrayData.length() >= 1) {
for (int i = 0; i < jsonArrayData.length(); i++) {
JSONObject object = new JSONObject(jsonArrayData.get(0));
// Setting value by key json
objObject.setAtrr(object.getString("YourKey"));
}
}
} catch (JSONException e) {
e.printStackTrace();
return null;
}
return objObject;
}

Categories

Resources