In my application I am receiving a JSON object as
{"secQueList":{"1":"Which is your favorite book?","2":"Who was your childhood hero?","3":"What is your pet's name?","4":"What make was your first car or bike?","5":"What is your favorite color?","6":"Which is your favorite sports team?","7":"What was the name of your school?","8":"What is your mother's maiden name?","9":"Which is your birthplace?","10":"Which is your favourite sport?","11":"Which is your favourite place of visit?"},"que1":null,"ans1":null,"message":null,"fieldErrors":null}
I am not able to figure out how exactly should i parse this object.
I tried using the below code but as this not a JSONArray it throws an exception.
String getParam(String code, String element){
try {
String base = this.getItembyID(code);
JSONObject product = new JSONObject(base);
JSONArray jarray = product.getJSONArray("item");
String param = jarray.getJSONObject(0).getString("name");
return param;
} catch (JSONException e) {
e.printStackTrace();
return "error";
}
}
I recommend you use sites for json formater which show to you the types of json elements as http://json.parser.online.fr/
and
you can use Gson library for parsing json by using pojo class
public class secQueList {
public String que1;
public int ans1;
public String message;
public String nextPage;
public QuestionList secQueList;
}
public class QuestionList {
#SerializedName("1")
public String ques1;
#SerializedName("2")
public int ques2;
#SerializedName("3")
public String ques3;
#SerializedName("4")
public String ques4;
#SerializedName("5")
public String ques5;
#SerializedName("6")
public String ques6;
#SerializedName("7")
public int ques7;
#SerializedName("8")
public String ques8;
#SerializedName("9")
public String ques9;
#SerializedName("10")
public String ques10;
#SerializedName("11")
public String ques11;
}
or you can use parse using built in JSON Object
String jsonBody = the string you want to parse
JSONObject quesJsonBody = new JSONObject(jsonBody);
JSONOBject quesJson = quesJsonBody.getJSONObject("secQueList");
String quesJson1 = quesJson.getString("1");
String quesJson2 = quesJson.getString("2");
String quesJson3 = quesJson.getString("3");
String quesJson4 = quesJson.getString("4");
String quesJson5 = quesJson.getString("5");
String quesJson6 = quesJson.getString("6");
String quesJson7 = quesJson.getString("7");
String quesJson8 = quesJson.getString("8");
String quesJson9 = quesJson.getString("9");
String quesJson10 = quesJson.getString("10");
String quesJson11 = quesJson.getString("11");
String que1 = quesJsonBody.getString("que1");
String ans1 = quesJsonBody.getString("ans1");
String message = quesJsonBody.getString("message");
String fieldErrors = quesJsonBody.getString("fieldErrors");
String base = this.getItembyID(code);
JSONObject product = new JSONObject(base);
JSONOBject secQueListJson = product.getJSONObject("secQueList");
// Get all json keys "1", "2", "3" etc in secQueList, so that we can get values against each key.
Set<Map.Entry<String, JsonElement>> entrySet = secQueListJson .entrySet ();
Iterator iterator = entrySet.iterator ();
for (int j = 0; j < entrySet.size (); j++) {
String key = null; //key = "1", "2", "3" etc
try {
Map.Entry entry = (Map.Entry) iterator.next ();
key = entry.getKey ().toString ();
//key = "1", "2", "3" etc
}
catch (NoSuchElementException e) {
e.printStackTrace ();
}
if (!TextUtils.isEmpty (key)) {
Log.d ("JSON_KEY", key);
String value = secQueListJson.getString(key);
//for key = "1", value = "Which is your favorite book?"
//for key = "2", value = "Who was your childhood hero?"
}
}
Try something like this:
JSONObject jsonObject = new JSONObject(code);
JSONObject jsonObject1 = jsonObject.getJSONObject("secQueList");
for (int i=0;i<jsonObject1.length();i++){
String msg = jsonObject1.getString(String.valueOf(i));
}
You can try to use Gson to parse it. I used code below in my App in similiar case:
ArrayList<String> myArrayList;
Gson gson = new Gson();
Type type = new TypeToken<ArrayList<String>>(){}.getType();
myArrayList= gson.fromJson(code, type);
You have to add gson to your build.grandle to have it working
compile 'com.google.code.gson:gson:2.2.+'
Extract Data from JSON String
public void ReadSMS_JSON(String JSON_String) {
String smsID = "";
String phone = "";
String message = "";
JSONObject jsonResponse = new JSONObject(JSON_String);
JSONArray jsonMainNode = jsonResponse.optJSONArray("tblsms");
if(jsonMainNode.length()>0){
JSONObject jsonChildNode = jsonMainNode.getJSONObject(0);
smsID = jsonChildNode.optString("sms_id");
phone = jsonChildNode.optString("sms_number");
message = jsonChildNode.optString("sms_message");
}
}
Related
I would like get countynames from the API and it returns nested objects;
"countries": {
"1": {
"name": "Cyprus",
"nameTurkish": "KKTC",
"nameNative": "Kıbrıs"
},
"2": {
"name": "Turkey",
"nameTurkish": "Türkiye",
"nameNative": "Türkiye"
},
"3": {
"name": "Monaco",
"nameTurkish": "Monako",
"nameNative": "Monaco"
},
and so on there are more than 200 countries and every county has its own "NUMBER_ID". In the end I want to list all "name" information. I think I should use JsonDeserializer but unfortunately I couldn't.
The entire JSON response can be read as a JSONObject that has multiple elements in it that you can iterate through and get different data.
String jsonResponse = ""; // Put the entire JSON response as a String
JSONObject root = new JSONObject(jsonResponse);
JSONArray rootArray = root.getJSONArray("countries"); // root element of the json respons
for (int i = 0; i < rootArray.length(); i++) {
JSONObject number = rootArray.getJSONObject(i);
String country = number.getString("name"); // Get country name
// Here you can add `country` into a List
}
UPDATE:
but there is no array in my JSON file, all of them are objects, every
country is in an object and every object has its own SerializedName
You can read it into JSONOjbect, and instead of using a JSONArray, you can iterate over the length of the JSONObject as below.
try {
JSONObject root = new JSONObject(jsonResponse);
JSONObject countries = root.getJSONObject("countries");
for (int i = 1; i <= countries.length(); i++) {
JSONObject number = countries.getJSONObject(String.valueOf(i));
String country = number.getString("name"); // Get country name
// Here you can add the `country` into a List
}
} catch (JSONException e) {
e.printStackTrace();
}
try using TypeToken.
Gson gson = new Gson();
List<Country> list = gson.fromJson(gson.toJson(what_you_get_data), new TypeToken<ArrayList<Country>>(){}.getType()); //Country is VO class what you make.
Here, you can see that your data looks like HashMap, so I just tried in that way and your data parsed successfully without a glitch:
Create Pojo's:
public class Countries {
private HashMap<String, Country> countries;
public HashMap<String, Country> getCountries() { return countries; }
public void setCountries(HashMap<String, Country> countries) { this.countries = countries; }
}
public class Country {
private String name;
private String nameTurkish;
private String nameNative;
public String getName() { return name; }
public void setName(String name) { this.name = name;}
public String getNameTurkish() { return nameTurkish; }
public void setNameTurkish(String nameTurkish) { this.nameTurkish = nameTurkish; }
public String getNameNative() { return nameNative; }
public void setNameNative(String nameNative) { this.nameNative = nameNative; }
}
Create a Gson Object and parse it:
Gson gson = new Gson();
// Countries Object
Type testC = new TypeToken<Countries>(){}.getType();
Countries ob = gson.fromJson(test, testC);
String newData = gson.toJson(ob.getCountries());
System.out.println("New Data: "+newData);
// All country in HashMap
Type country = new TypeToken<HashMap<String, Country>>(){}.getType();
HashMap<String, Country> countryHashMap = gson.fromJson(newData, country);
// Print All HashMap Country
for (Map.Entry<String, Country> set : countryHashMap.entrySet()) {
System.out.println("==> "+set.getKey() + " = " + set.getValue());
}
Output:
I/System.out: ==> 1 = Country{name='Cyprus', nameTurkish='KKTC', nameNative='Kıbrıs'}
I/System.out: ==> 2 = Country{name='Turkey', nameTurkish='Türkiye', nameNative='Türkiye'}
I/System.out: ==> 3 = Country{name='Monaco', nameTurkish='Monako', nameNative='Monaco'}
I'm using Android Networking and by using get, I get the data and this is the API that I'm calling.
String url = baseUrl + "atts_devices?device_serial=eq." + Build.SERIAL + "&select=*,subcompany_id{name}"
and getting the response like this
[{"permit_to_use":null,"min":null,"company_id":"4ed8954c-703e-41b5-94ba-eeb29546e3e3","model":"q1","bus_id":"b6d52ce3-3672-4230-9f9e-a6a465c1c8ea","sam_card":"04042DE2E52080","sim_number":null,"device_serial":"WP18121Q00000410","created_on":"2018-05-24T13:28:28.251004+00:00","remarks":null,"location_id":"ec176824-4cb7-4376-a436-429b529f8b45","id":"36bc07be-7d93-4209-ba15-9c9da7a58c3c","device_name":"wizarpos-ken","is_activated":"1","qrcode":null,"is_assigned":"1","sd_serial":"1510124e436172641068a36718010b00","updated_on":"2018-06-07T09:18:29.365416+00:00","software_serial":null,"subcompany_id":{"name":"MAN LINER"},"sim_serial":"89630317324030972665"}]
notice that subcompany_id has a another JSONArray. how can i get the name inside of it?
I'm using Android Fast Networking and this is the entire process
AndroidNetworking.get(baseUrl + "atts_devices?device_serial=eq." + Build.SERIAL + "&select=*,subcompany_id{name}")
.setPriority(Priority.HIGH)
.build()
.getAsJSONArray(new JSONArrayRequestListener() {
#Override
public void onResponse(JSONArray response) {
Log.e("response", String.valueOf(response));
try {
for (int i = 0; i < response.length(); i++) {
JSONObject jresponse = response.getJSONObject(i);
String raw_id = jresponse.get("id").toString();
String id_string = raw_id;
id_string = id_string.replace("\"", "");
String id_final = String.valueOf(id_string);
String raw_company_id = jresponse.get("company_id").toString();
String company_id_string = raw_company_id;
company_id_string = company_id_string.replace("\"", "");
String company_id_final = String.valueOf(company_id_string);
String raw_subcompany_id = jresponse.get("subcompany_id").toString();
String subcompany_id_string = raw_subcompany_id;
subcompany_id_string = subcompany_id_string.replace("\"", "");
String subcompany_id_final = String.valueOf(subcompany_id_string);
String raw_location_id = jresponse.get("location_id").toString();
String location_id_string = raw_location_id;
location_id_string = location_id_string.replace("\"", "");
String location_id_final = String.valueOf(location_id_string);
String raw_bus_id = jresponse.get("bus_id").toString();
String bus_id_string = raw_bus_id;
bus_id_string = bus_id_string.replace("\"", "");
String bus_id_final = String.valueOf(bus_id_string);
CompanyID = company_id_final;
BusID = bus_id_final;
subCompID = subcompany_id_final;
dbmanager.insertToDeviceInformation(id_final,
company_id_final,
subcompany_id_final,
location_id_final,
bus_id_final);
}
} catch (Throwable e) {
e.printStackTrace();
}
}
Make a new JSONObject JSONObject response = jresponse.get("subcompany_id"), then initialize your String name = response.get("name")
"subcompany_id":{"name":"MAN LINER"}
This is JSONObject not JSONArray, JSONArray start with [{ }]
So you can get "name" with JSONObject like this.
JSONObject jsonObjectSubCompanyId = jresponse.getJSONObject("subcompany_id");
String name = jsonObjectSubCompanyId.getString("name");
I print this json array in my android
It includes an array inside of an array
What is the android code?
This is my php output
[{"result":"true","user":[{"id":"26","name":"Manali Ashar","email":"123","password":"manali.ashar19#gmail.com","address":"chital road","city":"amreli","contact":"9402312345","qualification":"M.D","experience":"2","department":"Pediatric","age":"22","from_time":"05:15:00","to_time":"07:15:00","status":"1","current_date_time":"2016-04-02 07:18:26"}]}]
String data="[{"result":"true","user":[{"id":"26","name":"Manali Ashar","email":"123","password":"manali.ashar19#gmail.com","address":"chital road","city":"amreli","contact":"9402312345","qualification":"M.D","experience":"2","department":"Pediatric","age":"22","from_time":"05:15:00","to_time":"07:15:00","status":"1","current_date_time":"2016-04-02 07:18:26"}]}]";
try
{
JSONArray array=new JSONArray(data);
JSONObject jsonObject=array.getJSONObject(0);
String returnword=jsonObject.getString("return");
JSONArray users=jsonObject.getJSONArray("user");
for(int i=0;i<users.length();i++)
{
JSONObject object=users.getJSONObject(i);
String id=object.getString("id");
String name=object.getString("name");
String email=object.getString("email");
String password=object.getString("password");
String address=object.getString("address");
String city=object.getString("city");
String contact=object.getString("contact");
String qualification=object.getString("qualification");
String experience=object.getString("experience");
String department=object.getString("department");
String age=object.getString("age");
String from_time=object.getString("from_time");
String to_time=object.getString("to_time");
String status=object.getString("status");
String current_date_time=object.getString("current_date_time");
}
}
catch (JSONException e)
{
e.printStackTrace();
}
This is the simple way to parse any kind of json.
try to remove all array brackets [ ] because you need JSON Object only not array of json object. then data will look like
{"result":"true","user":{"id":"26","name":"Manali Ashar","email":"123","password":"manali.ashar19#gmail.com","address":"chital road","city":"amreli","contact":"9402312345","qualification":"M.D","experience":"2","department":"Pediatric","age":"22","from_time":"05:15:00","to_time":"07:15:00","status":"1","current_date_time":"2016-04-02 07:18:26"}}
now android code:
try {
JSONObject json = new JSONObject(result);
JSONObject user= json.getJSONObject("user");
String name= user.getString("name");
} catch (JSONException e) {
e.printStackTrace();
}
try {
//send response
JSONArray jsonArray = JSONArray(response);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
if(!jsonObject.isNull("result")){
String result = jsonObject.getString("result");
if(result.equals("true")){
JSONArray userArray = jsonObject.getJSONArray("user");
for(int j=0; j<userArray.length(); j++){
jsonObject = userArray.getJSONObject(j);
String id = isJsonValid(jsonObject, "id");
String name = isJsonValid(jsonObject, "name");
String email = isJsonValid(jsonObject, "email");
String password = isJsonValid(jsonObject, "password");
String address = isJsonValid(jsonObject, "address");
String city = isJsonValid(jsonObject, "city");
String contact = isJsonValid(jsonObject, "contact");
String qualification = isJsonValid(jsonObject, "qualification");
String experience = isJsonValid(jsonObject, "experience");
String department = isJsonValid(jsonObject, "department");
String to_time = isJsonValid(jsonObject, "to_time");
String age = isJsonValid(jsonObject, "age");
String from_time = isJsonValid(jsonObject, "from_time");
String status = isJsonValid(jsonObject, "status");
String current_date_time = isJsonValid(jsonObject, "current_date_time");
}
}else{
//do something
}
}
}
}catch (JSONException je){
je.printStackTrace();
}
public String isJsonValid(JSONObject jsonObject, String key) throws JSONException {
//check key is present or not
if(!jsonObject.isNull(key)){
return jsonObject.getString(key);
}else{
return "N/A";
}
}
You can make use of Gson library
Step 1: Create the POJO for the json data
public class Data {
public String result;
public List<User> user;
}
public class User {
public String status;
public String department;
public String password;
public String contact;
public String city;
public String id;
public String qualification;
public String email;
public String address;
public String from_time;
public String name;
public String age;
public String current_date_time;
public String experience;
public String to_time;
}
Step 2: Parse the JSON using Gson library
final Gson gson = new Gson();
Since it's a array of data, we need to get a List like this from the json string
List<Data> response = gson.fromJson(JSON_DATA, new TypeToken<List<Data>>() {}.getType());
Step 3: Get the values
Data data = response.get(0);
User user = data.user.get(0);
And print the result likewise
Log.d("JsonExample","Name: " + user.name);
...
...
I have a following json object, I could able to get plistDate, and pcategory, but I wonder how to parse each image object in the following json.
here is what I have so far
obj = new JSONObject(jsonObject);
listImages = obj.optString("images");
jsonObject
{
"plistDate": "2016-02-19 22:02:41",
"pcategory": "Kategori seciniz",
"images": {
"pimagePath": "products/138_1455940961.jpg",
"pimagePath2": "products/138_1455940961_2.jpg",
"pimagePath3": "products/138_1455940961_3.jpg",
"pimagePath4": "products/138_1455940961_4.jpg",
"pimagePath5": "products/138_1455940961_5.jpg"
}
}
images is inner object so you would have to retrieve it like that
JSONObject obj = new JSONObject("you jsin String");
String pcategory = obj.getString("pcategory");
String plistDate = obj.getString("plistDate");
JSONObject images_JsonObject = obj.getJSONObject("images");
String pimagePath = images_JsonObject.getString("pimagePath");
String pimagePath2 = images_JsonObject.getString("pimagePath2");
String pimagePath3 = images_JsonObject.getString("pimagePath3");
String pimagePath4 = images_JsonObject.getString("pimagePath4");
String pimagePath5 = images_JsonObject.getString("pimagePath5");
Update
JSONObject images_JsonObject = obj.getJSONObject("images");
Iterator<String> stringIterable = images_JsonObject.keys();
HashMap<String, String> hashMap = new HashMap<>();
ArrayList<String> list = new ArrayList<>();
while (stringIterable.hasNext()){
String key = stringIterable.next();
hashMap.put(key, images_JsonObject.getString(key));
list.add(images_JsonObject.getString(key));
}
I obtain a JSONObject from my server in my Android application through a service and in order to send to my activity I convert JSONObject to a string with
String myjson= gson.toJson(object);
b.putString("json", myjson);
And transfer the string to my activity where I recreate the JSONObject from String
Gson gson = new Gson();
JSONObject jobj = gson.fromJson(mydata, JSONObject.class);
JSONArray jarray = jobj.getJSONArray("myitems");
My JSON is as below
{"myitems":[{"event_id":"1","title":"Music launch party at makeover","description":"Music Launch function at Makeover","store_id":"2","user_id":"1","category_id":"1","submittedby":"store","start_date":"2015-02-03 09:00:01","end_date":"2015-02-03 20:00:00","price":"1000","gallery_1":"","gallery_2":"","gallery_3":"","add_lat":"30.693771","add_lon":"76.76486","distance":"10.329089177806534"},{"event_id":"2","title":"The Bacardi party at the New year bash","description":"Altius organizes a new year bash at their Night House.","store_id":"2","user_id":"1","category_id":"3","submittedby":"user","start_date":"2015-02-05 17:08:40","end_date":"2015-02-05 22:08:48","price":"2000","gallery_1":"","gallery_2":"","gallery_3":"","add_lat":"30.69461","add_lon":"76.76176","distance":"10.575941394542852"}]}
But I am getting error on getting jsonarray from the jsonobject. what should be the right way to obtain the jsonarray from the jsonobject or what wrong I am doing here.
Try the following :
Create a class containing a replica of the json objects
public class MyItem {
String event_id;
String title;
String description;
String store_id ;
String user_id;
String category_id;
String submittedby;
String start_date;
String end_date;
String price;
String gallery_1;
String gallery_2;
String gallery_3;
String add_lat;
String add_lon;
String distance;
public MyItem() {
}
}
In your case myjson is the string containing the json reply..so
JSONArray array = null;
try {
JSONObject jsonResp = new JSONObject(myjson);
array = jsonResp.getJSONArray("myitems");
} catch (JSONException e) {
e.printStackTrace();
}
Then you can iterate through the array and store objects in your custom class like so :
for(int i = 0; i < array.length(); i++){
JSONObject json2 = null;
try {
json2 = (JSONObject) array.get(i);
} catch (JSONException e) {
e.printStackTrace();
}
Gson gson = new Gson();
MyItem myItem = gson.fromJson(json2.toString(), MyItem.class);
//Do whatever you want with the object here
}