Create JSON android - android

I want to have an output like this
{"content":{
"A":["a1","a2","a3"],
"B":"b1String",
"C":["c1","c2"]}}
As of now, I am getting this.
{"content":{
"A":"[a1, a2, a3]",
"C":"[c1, c2]",
"B":"b1String"}}
Below is my code
Map <String, Object> myMap = new HashMap<String, Object>();
myMap.put("A",arrayOfA); //which is ArrayList<String>
myMap.put("B", myB1String);//which is String
myMap.put("C", arrayOfC);//which is ArrayList<String>
JSONObject jsonAll = new JSONObject(myMap);
Map <String, Object> mapAll = new HashMap<String, Object>();
mapAll.put("content", jsonAll);
JSONObject finalObject=new JSONObject(mapAll);
Log.e("JSON", finalObject.toString());
Any help woulld be much appreciated. Thanks

If you want to display it in an array then you need to add all your string arrays in a JSONArray and add it to the object to display it as an array.
sample:
JSONArray s2 = new JSONArray();
s2.put("a1");
s2.put("a2");
s2.put("a3");
myMap.put("A",s2); //which is ArrayList<String>
myMap.put("B", "b1String");//which is String
myMap.put("C", s2);
//which is ArrayList<String>
JSONObject jsonAll = new JSONObject(myMap);
Map <String, Object> mapAll = new HashMap<String, Object>();
mapAll.put("content", jsonAll);
JSONObject finalObject=new JSONObject(mapAll);
Log.d("JSON", finalObject.toString());
result:
{"content":{"A":["a1","a2","a3"],"B":"b1String","C":["a1","a2","a3"]}}

Try this way,hope this will help you to solve your problem.
String[] stringArrayOfA = new String[]{"a1","a2","a3"};
String[] stringArrayOfC = new String[]{"c1","c2"};
try {
JSONArray jsonArrayA = new JSONArray();
for (String str : stringArrayOfA){
jsonArrayA.put(str);
}
JSONArray jsonArrayC = new JSONArray();
for (String str : stringArrayOfC){
jsonArrayC.put(str);
}
JSONObject innerJsonobject = new JSONObject();
innerJsonobject.put("A",jsonArrayA);
innerJsonobject.put("B","b1String");
innerJsonobject.put("C",jsonArrayC);
JSONObject outerJsonObject = new JSONObject();
outerJsonObject.put("content",innerJsonobject);
Log.e("JSON", outerJsonObject.toString());
} catch (JSONException e) {
e.printStackTrace();
}
Result :{"content":{"A":["a1","a2","a3"],"B":"b1String","C":["c1","c2"]}}

Related

Android parse json array between json object

I tried to parse this json array and json objects but give me error and not recieve any data, can you help me to parse this;
Here my json link:
http://almahdishop.com/api/posts.json?fields=id,title,thumb&limit=10
Here My Code:
JSONArray jsonarray = new JSONArray(jsStr);
for (int i = 0; i <jsonarray.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
JSONObject jso = jsonarray.getJSONObject(i);
map.put("id_product", jso.getString("id"));
map.put("name", jso.getString("title"));
map.put("model","");
map.put("price", "14000");
map.put("oldprice", "14000");
map.put("logo", jso.getString("thumb"));
arraylist.add(map);
}
Some like this
try {
JSONObject data = new JSONObject(jsonString);
JSONArray itemsArray = data.getJSONArray("items");
for (int i = 0; i <itemsArray.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
JSONObject jso = itemsArray .getJSONObject(i);
map.put("id_product", jso.getString("id"));
map.put("name", jso.getString("title"));
map.put("model","");
map.put("price", "14000");
map.put("oldprice", "14000");
map.put("logo", jso.getString("thumb"));
arraylist.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
Parse this json as follows :
try {
JSONObject jsonObject = new JSONObject(jsonString);
JSONArray array = jsonObject.getJSONArray("items");
for(int i=0;i<array.length();i++){
JSONObject obj = (JSONObject) array.get(i);
}
} catch (JSONException e) {
e.printStackTrace();
}
I think problem comes from parsing.
Please use org.JSON.simple.-111.jar.

Parse list inside a json in android

I am putting a list in the json and now I want to get the list and display each entry in different textview. This is my code to put the list in json and to get the same
static ArrayList<String> list = new ArrayList<String>();
JSONObject json = jsonFruitArray.getJSONObject(i);
list.add("john");
list.add("mat");
list.add("jason");
json.put("sku",new JSONArray(list));
This is how i am trying to get the list
JSONArray jsonFruitSkuArray = json.getJSONArray("sku");
for(int iSku=0; iSku< jsonFruitSkuArray.length();iSku++){
JSONObject jsonSkuObject = jsonFruitSkuArray.getJSONObject(iSku);
productBean.setSkuId1(jsonSkuObject.getInt("sku"));
}
You should try like this. Use JsonArray
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("1", 1);
jsonObject.put("2", 2);
jsonObject.put("3", 3);
} catch (JSONException e) {
e.printStackTrace();
}
JSONArray result = new JSONArray();
result.put(jsonObject);
//Use json array
JSONObject jsonObj = new JSONObject();
JSONArray jsonArray = new JSONArray();
jsonArray.put("John");
jsonArray.put("Mat");
jsonArray.put("Jason");
jsonObj.put("json_array", jsonArray);
//Retrieve like this
JSONArray jsonFruitSkuArray = jsonObj.getJSONArray("json_array");
for(int iSku=0; iSku< jsonFruitSkuArray.length();iSku++){
JSONObject jsonSkuObject = jsonFruitSkuArray.getJSONObject(iSku);
productBean.setSkuId1(jsonSkuObject.getInt("sku"));
}
In your code you can try following :
ArrayList<String> list = new ArrayList<String>();
JSONObject json = new JSONObject();
list.add("john");
list.add("mat");
list.add("jason");
json.put("sku", new JSONArray(list));
JSONArray jsonFruitSkuArray = json.getJSONArray("sku");
for (int iSku = 0; iSku < jsonFruitSkuArray.length(); iSku++) {
String element = jsonFruitSkuArray.getString(iSku);
System.out.println(element);
}

Getting nested JSON array and objects and facing Json Exception

This is the Nested Json Array that we are getting as a respone from server side.
Response:
"[[{\"userID\":\"1\",\"roleID\":\"1\",\"userName\":\"GHG Admin\",\"email\":\"vikas.rana#redalkemi.in\",\"password\":\"b2314cd68cdfb7545dacd0b4ecf6a190\",\"userImage\":\"image12.jpg\",\"dtAdded\":\"2013-05-28\",\"dtUpdated\":\"2013-05-28\",\"enumStatus\":\"A\"}],[{\"settingID\":\"1\",\"moduleName\":\"event\",\"displayName\":\"Ev\\\"ent's1\",\"enumStatus\":\"E\"},{\"settingID\":\"2\",\"moduleName\":\"notice\",\"displayName\":\"Not\\\"ic'es\",\"enumStatus\":\"E\"},{\"settingID\":\"3\",\"moduleName\":\"quote\",\"displayName\":\"Qu\\\"ot'es\",\"enumStatus\":\"E\"},{\"settingID\":\"6\",\"moduleName\":\"crawlingtext\",\"displayName\":\"Crawling Text\",\"enumStatus\":\"D\"}]]"
Here is the code for getting this, but while executing complier goes in catch JSON exeception.
JSONArray arr;
try {
if (response != null) {
System.out.println(response);
arr= new JSONArray(response);
JSONArray a1= arr.getJSONArray(0);
JSONObject obj1= a1.getJSONObject(0);
map = new HashMap<String, String>();
// Retrive JSON Objects
map.put("userID", obj1.getString("userID"));
map.put("userName", obj1.getString("userName"));
data = new ArrayList<HashMap<String, String>>();
// Set the JSON Objects into the array
data.add(map);
id = (String) map.get("userID");
ID=Integer.parseInt(id);
name = (String) map.get("userName");
System.out.println(id+name);
JSONArray a2=arr.getJSONArray(1);
for (int i = 0; i < a2.length(); i++) {
JSONObject obj2= a2.getJSONObject(i);
map = new HashMap<String, String>();
map.put("settingID", obj2.getString("settingID"));
map.put("moduleName", obj2.getString("moduleName"));
data = new ArrayList<HashMap<String, String>>();
// Set the JSON Objects into the array
data.add(map);
String Module=(String)map.get("moduleName");
System.out.println("MODULE="+Module);
}}
}
catch ( JSONException e ) {
System.out.println("JSON Error parsing JSON");
}
It looks like you haven't removed the escape sequences from the JSON response before parsing it. Do this before you parse the response
response.toString().replaceAll("\\\\","");
arr= new JSONArray(response);
....

JSONObject parsing

Here is the way i was going to do it but I get an error in the line JSONObject c = orders.getJSONObject(i);:
Error:(95, 57) error: incompatible types: int cannot be converted to String
Maybe there is a better way of doing this process , please help
#Override
protected String doInBackground(String... params) {
try {
List<NameValuePair> param = new ArrayList<NameValuePair>();
JSONObject json = jsonParser.makeHttpRequest(URL_ORDERS, "GET",
param, token);
JSONObject data = json.getJSONObject("data");
JSONObject orders = data.getJSONObject("orders");
Log.d("JSON DATA", data.toString());
Log.d("JSON ORDERS", orders.toString());
for (int i = 0; i < orders.length(); i++) {
JSONObject c = orders.getJSONObject(i);
imageurl = c.getString(TAG_IMAGE);
Log.d("IDK", imageurl);
title = c.getString(TAG_TITLE).substring(0, 20);
price = c.getString(TAG_PRICE);
status = c.getString(TAG_PSTATUS);
symbol = c.getString(TAG_PRICESYMBOL);
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_TITLE, title);
map.put(TAG_PRICE, price);
map.put(TAG_PSTATUS, status);
map.put(TAG_PRICESYMBOL, symbol);
map.put(TAG_IMAGE, imageurl);
orderList.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
Your orders object is a JSONObject (with the order IDs being used as keys and the complete order objects as values), but in your code you're treating it as a JSONArray.
You probably want to change your loop as follows:
Iterator<String> orderIterator = orders.keys();
while (orderIterator.hasNext()) {
JSONObject c = orders.getJSONObject(orderIterator.next());
// ...
}
The call to keys() will return an iterator over the object's keys (in this case order IDs). Then it's just a matter of using the iterator to loop over all the keys, and retrieve each order object using getJSONObject.

How to get single row data from json response in android

Hello I am new to android,working on a snippet where I am getting my json data as
{"students":[{"id":"26","name":"aaa","abbr":"A"},{"id":"27","name":"bbb","abbr":"B"},{"id":"28","name":"ccc","abbr":"C"}]}
I want to get this record as single row, like id=26,name="aaa",abbr="A"
JSONObject json;
JSONArray jsonarray_student;
ArrayList<HashMap<String, String>> arraylist = new ArrayList<HashMap<String, String>>();
jsonarray_student = json.getJSONArray("students");
HashMap<String, String> map = new HashMap<String, String>();
map.put("id", json.getString("id"));
map.put("name", json.getString("name"));
map.put("abbr", json.getString("abbr"));
arraylist.add(map);
map will give me all id's all name's and all abbr's
Do i need to store them in List iterate???
Try this way,hope this will help you to solve your problem.
String response = "{\"students\":[{\"id\":\"26\",\"name\":\"aaa\",\"abbr\":\"A\"},{\"id\":\"27\",\"name\":\"bbb\",\"abbr\":\"B\"},{\"id\":\"28\",\"name\":\"ccc\",\"abbr\":\"C\"}]}}";
try{
ArrayList<HashMap<String, String>> studentList = new ArrayList<HashMap<String, String>>();
JSONObject responeJsonObject = new JSONObject(response);
JSONArray studentsJsonArry = responeJsonObject.getJSONArray("students");
for (int i=0;i<studentsJsonArry.length();i++){
HashMap<String, String> studentData = new HashMap<String, String>();
studentData.put("id", studentsJsonArry.getJSONObject(i).getString("id"));
studentData.put("name", studentsJsonArry.getJSONObject(i).getString("name"));
studentData.put("abbr", studentsJsonArry.getJSONObject(i).getString("abbr"));
studentList.add(studentData);
}
for (HashMap<String,String> student : studentList){
System.out.print("id"+student.get("id"));
System.out.print("name"+student.get("name"));
System.out.print("abbr"+student.get("abbr"));
}
}catch (Throwable e){
e.printStackTrace();
}
Yes there is a way for you to get in one line and my favorite is the use of the Gson Libray which will allow you to parse your string and get a list of object "Students" (List) where you then only need to do :
TextView id = (TextView) findViewById(R.Id.textview);
TextView name = (TextView) findViewById(R.Id.textview);
TextView abbr = (TextView) findViewById(R.Id.textview);
id.setText(student.getId());
name.setText(student.getName());
abbr.setText(student.getAbbr());
Where student is an entry in the List
Hope this can help you out with your problem =)

Categories

Resources