how to write java code of the json - android

I want to convert JSON into java code. My jsoncode as per given below.
{
"nodes": [
{
"node": {
"Name": "rahul Patel",
"Address": "\n\tAhmedabad",
"Date of Birth": "1991-05-03",
"Occupation": "developer",
"Member Since": "3 weeks 4 days"
}
}
]
java code
try {
JSONObject objResponse = new JSONObject(strResponse);
JSONArray jsonnodes = objResponse
.getJSONArray(nodes);
System.out.println("=hello this is DoinBackground");
for (i = 0; i < jsonnodes.length(); i++) {
System.out.println("hello this is for loop of DoinBackground");
JSONObject jsonnode = jsonnodes.getJSONObject(i);
JSONObject jsonnodevalue = jsonnode
.getJSONObject(node);
bean = new UserProfileBean();
bean.name = jsonnodevalue.getString(Name);
listActivities.add(bean);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
Here in logcat I print the value of before for loop System.out.println("=hello this is DoinBackground");,but value can't print under the for loop System.out.println("hello this is for loop of DoinBackground");
NOTE: Please let me know, Is it possible that we cannot used for loop in the code ? if yes then give the solution for that, There is another solution for this given problem.
Thanks.

Your json string is wrong. It must be trminated with }. Fix this and it will work.
Fixed json string:
{
"nodes": [
{
"node": {
"Name": "rahul Patel",
"Address": "\n\tAhmedabad",
"Date of Birth": "1991-05-03",
"Occupation": "developer",
"Member Since": "3 weeks 4 days"
}
}
]
}
Sample code to test:
String j = "{\r\n" +
" \"nodes\": [\r\n" +
" {\r\n" +
" \"node\": {\r\n" +
" \"Name\": \"rahul Patel\",\r\n" +
" \"Address\": \"\\n\\tAhmedabad\",\r\n" +
" \"Date of Birth\": \"1991-05-03\",\r\n" +
" \"Occupation\": \"developer\",\r\n" +
" \"Member Since\": \"3 weeks 4 days\"\r\n" +
" }\r\n" +
" }\r\n" +
" ]\r\n" +
"}";
try{
JSONObject objResponse = new JSONObject(j);
JSONArray jsonnodes = objResponse.getJSONArray("nodes" );
for (int i = 0; i < jsonnodes.length(); i++) {
JSONObject jsonnode = jsonnodes.getJSONObject(i);
JSONObject jsonnodevalue = jsonnode
.getJSONObject("node");
Log.v("name", jsonnodevalue.getString("Name"));
Log.v("address", jsonnodevalue.getString("Address"));
Log.v("occupation", jsonnodevalue.getString("Occupation"));
}
}
catch (Exception e) {
e.printStackTrace();
}

Try using Gson - http://code.google.com/p/google-gson/. Will save a lot of headache.
In your code, however make sure that your JSON string is being parsed properly.
Just to be sure objResponse.getJSONArray(nodes) should be objResponse.getJSONArray("nodes")

Related

How to parse following JSOn DATA

[
{
"ORDERID": [
"Epp144534354354",
"Epp14453sdfgsfd",
"Epp14487484",
"Epp144454464646"
],
"ADDRESS": " MUMBAI",
"FOLLOW_UPDATE": "25/5/2017",
"SIGN_IMAGE": "sign.png",
"DATE_TIME": "2017-05-02 17:52:09.0",
"EMAIL": "abhi#abhi.con",
"IMAGE_1": "image1.jpg",
"COMMENT": "gshshshsh",
"IMAGE_3": "image3.jpg",
"NAME": "abhi",
"MOBILE": "22416545",
"IMAGE_2": "image2.jpg"
}
]
I want to parse above json data then how to parse the json in android how to parse code in java
You can try this.Here is JSON parsing in android.
String response=" [\n" +
"{ \"ORDERID\": [ \"Epp144534354354\", \"Epp14453sdfgsfd\", \"Epp14487484\", \"Epp144454464646\"],\n" +
"\n" +
"\"ADDRESS\": \" 26, Wakad Road Samarth Colony, Omkar Society, Pimple Nilakh Pimpri-Chinchwad, Maharashtra 411027\",\n" +
"\n" +
"\"FOLLOW_UPDATE\": \"25/5/2017\",\n" +
"\n" +
"\"SIGN_IMAGE\": \"http://192.168.0.108:8084/MarketingApplicationImages/IMAGES//sign.png\",\n" +
"\n" +
"\"DATE_TIME\": \"2017-05-02 17:52:09.0\",\n" +
"\n" +
"\"EMAIL\": \"abhi#abhi.con\",\n" +
"\n" +
"\"IMAGE_1\": \"http://192.168.0.108:8084/MarketingApplicationImages/IMAGES//image1.jpg\",\n" +
"\n" +
"\"COMMENT\": \"gshshshsh\",\n" +
"\n" +
"\"IMAGE_3\": \"http://192.168.0.108:8084/MarketingApplicationImages/IMAGES//image3.jpg\",\n" +
"\n" +
"\"NAME\": \"abhi\",\n" +
"\n" +
"\"MOBILE\": \"8149608493\",\n" +
"\n" +
"\"IMAGE_2\": \"http://192.168.0.108:8084/MarketingApplicationImages/IMAGES//image2.jpg\"\n" +
" }]";
try {
JSONArray jArray=new JSONArray(response);
for (int i = 0; i <jArray.length() ; i++) {
JSONObject jonj=jArray.getJSONObject(i);
JSONArray orderArray=jonj.getJSONArray("ORDERID");
for (int j = 0; j <orderArray.length(); j++) {
Log.e("array value"," ..... "+orderArray.getString(i));
}
Log.e("address"," ..... "+jonj.getString("ADDRESS"));
Log.e("FOLLOW_UPDATE"," ..... "+jonj.getString("FOLLOW_UPDATE"));
Log.e("SIGN_IMAGE"," ..... "+jonj.getString("SIGN_IMAGE"));
}
} catch (JSONException e) {
e.printStackTrace();
}
To parse json please follow this basic rules which will help you in long run.
First check if json is valid or not, paste your json response and click validate json.
To view json content in proper format to understand better use paste your data in text section and switch to view section to view it.
Then use GSON library to parse the data(refer any online tutorial)
You would require pojo's for GSON use paste json response in the text box section which is located on the left hand side and then on the right hand side set source type as JSON annotation type as GSON and click on the preview at the bottom of the page, copy it and use it.

JSONObject.toString() converts internal JSONArray as string in Android

I am creating a JSON request as followed:
JSONObject request = new JSONObject();
request.put("ID", "35");
request.put("password", "password");
List<JSONObject> fieldList = new ArrayList<>();
for (int i = 0; i < 3; i++) {
fieldList.add(new JSONObject()
.put("unitid", "unitid " + i)
.put("price", "Price " + i));
}
request.put("unitsummary", new JSONObject()
.put("unitsummarydetail", fieldList)
);
String requestString = request.toString();
The value of requestString variable should be :
{
"ID": "35",
"password": "password",
"unitsummary": {
"unitsummarydetail": [
{
"price": "Price 0",
"unitid": "unitid 0"
},
{
"price": "Price 1",
"unitid": "unitid 1"
},
{
"price": "Price 2",
"unitid": "unitid 2"
}
]
}
}
But it is :
{
"ID": "35",
"password": "password",
"unitsummary": {
"unitsummarydetail": "[{\"unitid\":\"unitid 0\",\"price\":\"Price 0\"}, {\"unitid\":\"unitid 1\",\"price\":\"Price 1\"}, {\"unitid\":\"unitid 2\",\"price\":\"Price 2\"}]"
}
}
It is converting the unitsummarydetail as string.
I have tried but didn't find similar issue or any solution on internet.
Is there any issue in my code or this is the behavior of library?
Any ideas or solution code snippets are welcome.
Thanks.
Use JSONArray instead of ArrayList.
JSONObject request = new JSONObject();
request.put("ID", "35");
request.put("password", "password");
JSONArray fieldList = new JSONArray();
for (int i = 0; i < 3; i++) {
fieldList.put(new JSONObject() .put("unitid", "unitid " + i) .put("price", "Price " + i));
}
request.put("unitsummary", new JSONObject() .put("unitsummarydetail", fieldList) );
String requestString = request.toString();
Output:
{"ID":"35","password":"password","unitsummary":{"unitsummarydetail":[{"unitid":"unitid
0","price":"Price 0"},{"unitid":"unitid 1","price":"Price
1"},{"unitid":"unitid 2","price":"Price 2"}]}}
change your code
from
request.put("unitsummary", new JSONObject()
.put("unitsummarydetail", fieldList));
to
request.put("unitsummary", new JSONObject()
.put("unitsummarydetail", new JSONArray(fieldList)));
Crazy !!!!
JsonArray treatIdArray = new JsonArray(); // this one will result string : "["id", "id"]"
JSONArray treatIdArray = new JSONArray(); // this one will result array : ["id", "id"]
They are 2 different Json, lol, com.google.gson.JsonArray vs org.json.JSONArray and it took me almost a day. Oh my God !!!!
you could create a JSON array unitsummarydetail and add all the json objects unitsummary in a for loop

parse JSON response and add it into List

I've got problem with parsing JSON. I've got response from webservice like this :
{
   "data": {
      "1": [
         {
            "id": "2",
            "name": "Szelki bezpieczeństwa",
            "quantity": "1",
            "note": null,
            "picture_id": null,
            "code": "CCCCCCCCCCCCCC"
         },
         {
            "id": "3",
            "name": "Kalosze do brodzenia, wysokie lub biodrowe",
            "quantity": "2",
            "note": "Do wymiany",
            "picture_id": null,
            "code": "DDDDDDDDDDDDDD"
         }
      ],
      "2": [
         {
            "id": "1",
            "name": "Spodnie dla pilarza z ochroną przed przecięciem, klasa min. 1 (wg PN-EN 381-5)",
            "quantity": "2",
            "note": "Uszkodzone",
            "picture_id": null,
            "code": "DAAD086F690E1C36"
         }
      ]
   }
}
I try to parse it into PART object and add it to List but somewhere I'm making mistake because object is not being parsed.
public void onResponse(String response) {
Log.e(TAG, "onResponse WHOLE: " + response);
try {
JSONObject responseJSONObject = new JSONObject(response);
String arrayString = responseJSONObject.getJSONArray("data").toString();
JSONArray responseJSONArray = new JSONArray(arrayString);
Part tempCarEquipment;
int index = 1;
for (int i = 0; i < responseJSONArray.length(); i++,index++) {
JSONObject object = responseJSONArray.getJSONObject(index);
JSONArray response2 = object.getJSONArray(Integer.toString(index));
String id = object.getJSONObject(Integer.toString(i)).getString("id");
String name= object.getJSONObject(Integer.toString(i)).getString("name");
String quantity= object.getJSONObject(Integer.toString(i)).getString("quantity");
String picture_id= object.getJSONObject(Integer.toString(i)).getString("picture_id");
String code= object.getJSONObject(Integer.toString(i)).getString("code");
tempCarEquipment = new Part(name,quantity,"",picture_id,code,id,"",0);
wholeList.add(tempCarEquipment);
Log.e(TAG, "wholeList: " + wholeList.size());
}
} catch (JSONException e) {
e.printStackTrace();
}
}
Thanks in advance fo every help! :)
JSON Parsing
You have to use the iterator for this kind of response
basic example of iterator is in this link.
You are trying to parse map as an array here:
String arrayString = responseJSONObject.getJSONArray("data").toString();
Try something like this instead:
List<JSONArray> objects = new ArrayList<>();
Iterator<String> keys = responseJSONObject.getJSONObject("data").keys();
while(keys.hasNext()) {
objects.add(responseJSONObject.getJSONObject("data").get(keys.next());
}
// rest of your stuff
Alternatively, consider using GSON to parse JSON responses using POJOs.

JSONObject to JSONArray with days as keys

I have the following sample json:
{\"2013-05-30\":{\"available\":\"1\",\"bind\":0,\"info\":\"\",\"notes\":\"\",\"price\":\"\",\"promo\":\"\",\"status\":\"available\"},
\"2013-05-31\":{\"available\":\"1\",\"bind\":0,\"info\":\"\",\"notes\":\"\",\"price\":\"\",\"promo\":\"\",\"status\":\"available\"},
\"2013-06-01\":{\"available\":\"1\",\"bind\":0,\"info\":\"\",\"notes\":\"\",\"price\":\"\",\"promo\":\"\",\"status\":\"available\"}}
I read this into a String and then parse it into a JSONObject, but I need it to be in a JSONArray.
I have tried adding programmatically "[" at the beginning of the string and "]" at the end of it, before I convert it into a JSONArray, and, although it recognizes it as an Array, it still sees it as a single object (I only seem to have JSONArray(0)).
This is how I try to parse the jsonData as an Array:
try{
jArray = new JSONArray(resultString);
for(int i=0;i<jArray.length();i++){
JSONObject json_data = jArray.getJSONObject(i);
Log.i("log_4","Available: "+json_data.getString("available")+
", Bind: "+json_data.getString("bind")+
", Info: "+json_data.getString("info") +
", Notes: "+json_data.getString("notes") +
", Price: "+json_data.getString("price") +
", Promo: "+json_data.getString("promo") +
", Status: "+json_data.getString("status")
);
}
}catch(JSONException e){
Log.e("log_5", "Error parsing data "+e.toString());
}
and here is the version in which I don't add [ and ], therefore parsing it as a JSONObject.
try {
jsonResponse = new JSONObject(resString);
} catch (JSONException e) {
Log.e("log_3", "Error parsing data "+e.toString());
}
How can I separate each day (e.g."2013-05-30") into a different object, with each object having as key the value of the day?
Thanks a lot!
Instead of adding a [ at the begining and a ] at the end, try replacing the first instance of { with [ and the last instance of } with ] and then making a JSONArray out of it.

JSON data to android application

I got this part inside my json object. But I couldn't get this as a java List. It give error. So I tried to take it as a String Array. But it was same as before. So what should I use to parse this data to use with my android application ?
cuisine: {
-cuisine_names: [
"All (36)"
"Malaysian/ Singaporean (1)"
"Asian (1)"
"Australian (2)"
"Chinese (1)"
"European (3)"
"Spanish (1)"
"Greek (2)"
"Steak House (1)"
"Indian (1)"
"International (7)"
"Thai (1)"
"Italian (8)"
"Modern Australian (7)"
]
-price_ranges: [
"Any Price"
"$0-15"
"$15-30"
"$30+"
]
-times: [
"Any Time"
"05:30PM"
"06:00PM"
"06:30PM"
"07:00PM"
"07:30PM"
"08:00PM"
"08:30PM"
"09:00PM"
"09:30PM"
"10:00PM"
"10:30PM"
"11:00PM"
"11:30PM"
]
}
Thanks in advance !
To fill a list with a JSONObject, you should use a function like this (where NewsBSR is a custom object with some basic fields):
private ArrayList<NewsBSR> getListObjectsNews(JSONObject objNews)
{
ArrayList<NewsBSR> listNews = new ArrayList<NewsBSR>();
try{
for (Iterator iterator = objNews.keys(); iterator.hasNext();)
{
String cle = String.valueOf(iterator.next());
Object objet = objNews.get(String.valueOf(cle));
Log.v("V", "News: "+cle+ " : "+objet.toString());
if (cle.equals("results"))
{
JSONArray array = objNews.getJSONArray(cle);
for(int i = 0; i < array.length() ; i++)
{
Object obj = array.get(i);
Iterator it = ((JSONObject) obj).keys();
NewsBSR news = new NewsBSR();
while (it.hasNext())
{
String k = String.valueOf(it.next());
String val = ((JSONObject) obj).getString(k);
Log.v("V", "Array content : "+k+ " : "+val);
if (k.equals("tt") && val.length() > 0)
{
news.setTitle(val);
}
if (k.equals("dt") && val.length() > 0)
{
news.setDate(UtilsDate.stringToDate(val));
}
if (k.equals("num") && val.length() > 0)
{
news.setId(val);
}
}
listNews.add(news);
}
}
}
} catch (Exception e) {
// TODO Auto-generated catch block
Log.v("V", "Error HOME: "+ e.getMessage());
e.printStackTrace();
}
return (listNews);
}
I think you have forgotten put commas. And you can use this
http://www.androidcompetencycenter.com/2009/10/json-parsing-in-android/
The json format is not supposed to be like that.
first, there should be a root object surrounding the codes like this.
{ <---this
cuisine: {
-cuisine_names: [
"All (36)"........
} <-- and this
and then you need commas between every string in the array like so
"Australian (2)",
"Chinese (1)",
"European (3)",
"Spanish (1)",
"Greek (2)",
"Steak House (1)",
It's very simple with Gson:
public class Foo
{
static String jsonInput =
"{" +
"\"cuisine\": {" +
"\"cuisine_names\": [" +
"\"All (36)\"," +
"\"Malaysian/ Singaporean (1)\"," +
"\"Asian (1)\"," +
"\"Australian (2)\"," +
"\"Chinese (1)\"," +
"\"European (3)\"," +
"\"Spanish (1)\"," +
"\"Greek (2)\"," +
"\"Steak House (1)\"," +
"\"Indian (1)\"," +
"\"International (7)\"," +
"\"Thai (1)\"," +
"\"Italian (8)\"," +
"\"Modern Australian (7)\"" +
"]," +
"\"price_ranges\": [" +
"\"Any Price\"," +
"\"$0-15\"," +
"\"$15-30\"," +
"\"$30+\"" +
"]," +
"\"times\": [" +
"\"Any Time\"," +
"\"05:30PM\"," +
"\"06:00PM\"," +
"\"06:30PM\"," +
"\"07:00PM\"," +
"\"07:30PM\"," +
"\"08:00PM\"," +
"\"08:30PM\"," +
"\"09:00PM\"," +
"\"09:30PM\"," +
"\"10:00PM\"," +
"\"10:30PM\"," +
"\"11:00PM\"," +
"\"11:30PM\"" +
"]" +
"}" +
"}";
public static void main(String[] args)
{
GsonBuilder gsonBuilder = new GsonBuilder();
Gson gson = gsonBuilder.create();
CuisineContainer cc = gson.fromJson(jsonInput, CuisineContainer.class);
System.out.println(cc);
}
}
class CuisineContainer
{
private Cuisine cuisine;
#Override
public String toString()
{
return cuisine.toString();
}
}
class Cuisine
{
private String[] cuisine_names;
private String[] price_ranges;
private String[] times;
#Override
public String toString()
{
StringBuilder result = new StringBuilder();
result.append("cuisine_names: ");
result.append(Arrays.asList(cuisine_names));
result.append(System.getProperty("line.separator"));
result.append("price_ranges: ");
result.append(Arrays.asList(price_ranges));
result.append(System.getProperty("line.separator"));
result.append("times: ");
result.append(Arrays.asList(times));
return result.toString();
}
}
output:
cuisine_names: [All (36), Malaysian/ Singaporean (1), Asian (1), Australian (2), Chinese (1), European (3), Spanish (1), Greek (2), Steak House (1), Indian (1), International (7), Thai (1), Italian (8), Modern Australian (7)]
price_ranges: [Any Price, $0-15, $15-30, $30+]
times: [Any Time, 05:30PM, 06:00PM, 06:30PM, 07:00PM, 07:30PM, 08:00PM, 08:30PM, 09:00PM, 09:30PM, 10:00PM, 10:30PM, 11:00PM, 11:30PM]

Categories

Resources