How do I use JSONObject in Android - android

I have the following Android java code:
String json = "{\"Name_1\":1,\"Name_2\":0,\"Name_3\":0}";
JSONObject object = new JSONObject(json);
String[] propertyNames = JSONObject.getNames(object);
values = new String[propertyNames.length];
for (int i = 0; i < propertyNames.length; i++) {
values[i] = String.valueOf(object.get(propertyNames[i]));
}
but I am getting the following error: The method getNames(JSONObject) is undefined for the type JSONObject.
What can I do to get the propertyNames?

Why not look at the JavaDoc? It tells you about the keys() method.
for (Iterator<String> it = object.keys(); it.hasNext(); ) {
String key = it.next();
// ...
}
Edit: get an array of keys:
List<String> keyList = new ArrayList<String>();
for (Iterator<String> it = object.keys(); it.hasNext(); ) {
String key = it.next();
keyList.add(key);
}
String[] keyArray = keyList.toArray(new String[keyList.size()]);

Related

How to convert JSONObject to Hashmap?

String jsonString = "{"name":"kd","isMe":"yes","time":"10:12 AM"},{"name":"you","isMe":"no","time":"10:12 AM"}";
JSONObject jValueObject = new JSONObject(jsonString);
Iterator<?> values = jValueObject.keys();
while(values.hasNext()){
String final_key = (String)values.next();
String final_value = jValueObject.getString(final_key);
if (final_value != "")
map.put(final_key, final_value);
if (!final_key.equals("")) {
sbkeys.append(final_key).append(',');
}
}
Log.e("Final_Map", String.valueOf(map));
itemList = sbkeys.toString();
Output : {name=kd,isMe=yes,time=10:12 AM}
Try this code:
HashMap map = new HashMap<String, String>();
Iterator<?> values = jValueObject.keys();
while(values.hasNext()) {
String final_key = (String)values.next();
String final_value = jValueObject.optString(final_key, "");
if (!final_value.equals(""))
map.put(final_key, final_value);
}
for (k : map.keySet()) {
Log.d("Final_Map", "map[" + key + "] : " + map.get(k));
}
this is a duplicate question,
please check these answers
Convert JSONObject to Map
use Jackson(http://jackson.codehaus.org/) from http://json.org/
HashMap<String,Object> result =
new ObjectMapper().readValue(<JSON_OBJECT>, HashMap.class);
or
You can use Gson() (com.google.gson) library if you find any difficulty using Jackson.
HashMap<String, Object> yourHashMap = new Gson().fromJson(yourJsonObject.toString(), HashMap.class);
First off, if its a json array that you need in the string then wrap your string in square brackets. (I'd expect you've escaped the double quotes as well).
String jsonString = "[{\"name\":\"kd\",\"isMe\":\"yes\",\"time\":\"10:12 AM\"},{\"name\":\"you\",\"isMe\":\"no\",\"time\":\"10:12 AM\"}]";
Now its a JSONArray and not a JSONObject. So to get a list of Maps,
JSONArray jValueArray = new JSONArray(jsonString);
List<Object> listOfMaps = jValueArray.toList();
System.out.println(listOfMaps);
Prints:
[{isMe=yes, name=kd, time=10:12 AM}, {isMe=no, name=you, time=10:12 AM}]
JSONObject jObject = new JSONObject(jsonString);
Iterator<?> keys = jObject.keys();
while (keys.hasNext()) {
map = new HashMap<String, String>();
sbkeys = new StringBuilder();
String key = (String) keys.next();
String value = jObject.getString(key);
try{
JSONObject jValueObject = new JSONObject(value);
Iterator<?> values = jValueObject.keys();
while (values.hasNext()) {
String final_key = (String) values.next();
String final_value = jValueObject.getString(final_key);
if (!final_value.equalsIgnoreCase("")) {
map.put(final_key, final_value);
sbkeys.append(final_key).append(',');
}
}
}catch (Exception e){
e.fillInStackTrace();
}
try {
//// Your Code..
} catch (Exception e) {
errorCode = "1";
}
}

Store json array keys data in separate arrayLists

I have this kind of json data returning from url as shown in Image1 Image2 Image3
Basically there are dates inside data and then within these dates there are further 5 different things i.e. session_from, session_to, rate, bookingFound and promotion. What i want is that i want to store all these dates data in separate arraylist.
For example:
sessionfrom0 contains data for 09-09-2018 and all its objects
sessionfrom1 contains data for 10-09-2018 and all its objects
sessionfrom2 contains data for 11-09-2018 and all its objects
I have tried with following piece of code but its not working correctly
JSONObject jsonObject = new JSONObject(response);
JSONObject dataObj = jsonObject.getJSONObject("data");
Iterator<String> iter = dataObj.keys();
sessionsfrom0 = new ArrayList<String>();
sessionsfrom1 = new ArrayList<String>();
sessionsfrom2 = new ArrayList<String>();
while (iter.hasNext()) {
key = iter.next();
JSONArray datesArray = dataObj.getJSONArray(key);
for (int i = 0; i < datesArray.length(); i++) {
JSONObject datesObject0 = datesArray.getJSONObject(i);
JSONObject datesObject1 = datesArray.getJSONObject(i);
JSONObject datesObject2 = datesArray.getJSONObject(i);
sessionsfrom0.add(datesObject0.getString("session_from") + " - " +datesObject0.getString("session_to");
sessionsfrom1.add(datesObject1.getString("session_from") + " - " +datesObject1.getString("session_to");
sessionsfrom2.add(datesObject2.getString("session_from") + " - " +datesObject2.getString("session_to");
} }
This code not working correctly, as you can see that date 09-09-2018 contains further array of size 4 and and in those array there are further 5 items inside each jjson object so i want to store all this in first arraylist i.e. sessionfrom0 and then go to next date and pick all its arrays and json objects and store data in sessionfrom1 arraylist and so on.
Try this:
JSONObject jsonObject = new JSONObject(response);
JSONObject dataObj = jsonObject.getJSONObject("data");
Iterator<String> iter = dataObj.keys();
sessionsfrom0 = new ArrayList<String>();
sessionsfrom1 = new ArrayList<String>();
sessionsfrom2 = new ArrayList<String>();
while (iter.hasNext()) {
String key = iter.next();
JSONArray datesArray = dataObj.getJSONArray(key);
switch (key) {
case "2018-09-09":
fillSessions(datesArray, sessionsfrom0);
break;
case "2018-10-09":
fillSessions(datesArray, sessionsfrom1);
break;
....so on....
}
}
You can create a function instead of rewriting the for loop logic on each case:
void fillSessions(JSONArray jsonArray, List<String> sessionList) {
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject datesObject = jsonArray.getJSONObject(i);
sessionList.add(datesObject.getString("session_from") + " - " +datesObject0.getString("session_to");
}
}
You can do this by using HashMap
JSONObject jsonObject = new JSONObject(response);
JSONObject dataObj = jsonObject.getJSONObject("data");
Iterator<String> iter = dataObj.keys();
HashMap<String, ArrayList<String>> map = new HashMap<>();
while (iter.hasNext()) {
key = iter.next();
JSONArray datesArray = dataObj.getJSONArray(key);
ArrayList<String> list = new ArrayList<>();
for (int i = 0; i < datesArray.length(); i++) {
JSONObject datesObject0 = datesArray.getJSONObject(i);
list.add(datesObject0.getString("session_from") + " - " + datesObject0.getString("session_to");
}
map.put(key, list);
}
Try this:
JSONObject jsonObject = new JSONObject(response);
JSONObject dataObj = jsonObject.getJSONObject("data");
Iterator<String> iter = dataObj.keys();
Map<String, ArrayList<String>> map = new TreeMap<>();
while (iter.hasNext()) {
String key = iter.next();
JSONArray datesArray = dataObj.getJSONArray(key);
ArrayList<String> tmp = new ArrayList<>();
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject datesObject = jsonArray.getJSONObject(i);
tmp.add(datesObject.getString("session_from") + " - "+datesObject.getString("session_to"));
}
map.put(key, tmp);
}
Probably you don't have all keys inside data so using switch case is not sensitive.

parse JsonArray in android

How to parse this jsonarray "Images" ??
I parse this json ,, but i can't get "Images"
the Jsonarray "data" inside it elements , inside every element array of images >>>>
this is the response
this is my code
JSONObject responseObject = new JSONObject(response);
JSONArray newsJsonArray = responseObject.getJSONArray("data");
final List <AndroidVersion> newsList = new ArrayList <AndroidVersion>();
newsImages = new ArrayList<String>();
newsids = new ArrayList<String>();
newsnames = new ArrayList<String>();
newshotelsid = new ArrayList<String>();
newscontents = new ArrayList<String>();
newstimesto = new ArrayList<String>();
newscost = new ArrayList<String>();
newstimesfrom = new ArrayList<String>();
newscountry = new ArrayList<String>();
newscity = new ArrayList<String>();
newstype = new ArrayList<String>();
newsImages = new ArrayList<String>();
for (int j = 0; j < newsJsonArray.length(); j++) {
AndroidVersion news = new AndroidVersion();
if (newsJsonArray.getJSONObject(j).has("id")) {
newsids.add(newsJsonArray.getJSONObject(j).getString("id"));
}
if (newsJsonArray.getJSONObject(j).has("name")) {
news.setName(newsJsonArray.getJSONObject(j).getString("name"));
newsnames.add(newsJsonArray.getJSONObject(j).getString("name"));
}
if (newsJsonArray.getJSONObject(j).has("desc")) {
news.setdesc(newsJsonArray.getJSONObject(j).getString("desc")
.replaceAll("<p>", "").replaceAll("<\\/p>\\r\\n", "").replaceAll(" ", ""));
newscontents.add(newsJsonArray.getJSONObject(j).getString("describtion"));
}
if (newsJsonArray.getJSONObject(j).has("country")) {
news.setcountry(newsJsonArray.getJSONObject(j).getString("country"));
newscountry.add(newsJsonArray.getJSONObject(j).getString("country"));
}
if (newsJsonArray.getJSONObject(j).has("city")) {
news.setcity(newsJsonArray.getJSONObject(j).getString("city"));
newscity.add(newsJsonArray.getJSONObject(j).getString("city"));
}
if (newsJsonArray.getJSONObject(j).has("date_from")) {
news.setdate_from(newsJsonArray.getJSONObject(j).getString("date_from"));
newstimesfrom.add(newsJsonArray.getJSONObject(j).getString("date_from"));
}
if (newsJsonArray.getJSONObject(j).has("date_to")) {
news.setdate_to(newsJsonArray.getJSONObject(j).getString("date_to"));
newstimesto.add(newsJsonArray.getJSONObject(j).getString("date_to"));
}
if (newsJsonArray.getJSONObject(j).has("num persons")) {
news.sethotel_id(newsJsonArray.getJSONObject(j).getString("num persons"));
newshotelsid.add(newsJsonArray.getJSONObject(j).getString("num persons"));
}
if (newsJsonArray.getJSONObject(j).has("price")) {
news.setprice(newsJsonArray.getJSONObject(j).getString("price"));
newscost.add(newsJsonArray.getJSONObject(j).getString("price"));
}
if (newsJsonArray.getJSONObject(j).has("images")) {
news.setImage(newsJsonArray.getJSONObject(j).getString("images"));
newsImages.add(newsJsonArray.getJSONObject(j).getString("images"));
}
newsList.add(news);
}
I would highly recommend using Gson to parse it.
Create a response object with structure matching the json response. Then you can use the single object without having to create it down into parts.
Change this part:
if (newsJsonArray.getJSONObject(j).has("images")) {
news.setImage(newsJsonArray.getJSONObject(j).getString("images"));
newsImages.add(newsJsonArray.getJSONObject(j).getString("images"));
}
to:
if(newsJsonArray.getJSONObject(j).getJSONArray("images") != null) {
JSONArray jArray = newsJsonArray.getJSONObject(j).getJSONArray("images");
for (int k=0; k<jArray.length(); k++) {
news.setImage(jArray.getString(k));
newsImages.add(jArray.getString(k));
}
}
You can use direct string object from JSONArray like below:
JSONArray array = object.getJSONArray("images");
for (int i = 0; i < array.length(); i++) {
String image = array.getString(i);
}

How To store json values in a set of arrays in android

i have a json file like so :
http://da.pantoto.org/api/files
i want to store these values in variables to be used later. The values should be stored in some String array variables like id[], uploadDate[], url[].
i can find examples using ListView and ArrayAdapter. but thats not what i really want. Anyone can help??
This is only an example to show how you can get the values from JSON. You need to store these values as you need.
JSONObject jsonObject = new JSONObject("your response");
JSONArray filedetails = jsonObject.getJSONArray("files");
for(int i=0; i<filedetails.size();i++){
String id = filedetails.get(i).getString("id");
JSONArray tagsdetails= filedetails.get(i).getJSONArray("tags");
for(int i=0; i<tagsdetails.size();i++){
//fetch values in it
}
}
You can't do it exactly that way, You have to iterate trough the array and get each object properties individually and then if you want you could create an array to store each object property.
//From the example: http://da.pantoto.org/api/files
JSONArray files = null;
//Creating service handler class instance
ServiceHandler sh = new ServiceHandler();
//Making a request to url and getting response
String jsonStr = sh.makeServiceCall("http://da.pantoto.org/api/files", ServiceHandler.GET);
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
files = jsonObj.getJSONArray("files");
//YOUR NEW ARRAY
String[] ids = new String[20];
String[] urls = new String[20];
//etc
//looping through All files
for (int i = 0; i < files.length(); i++) {
JSONObject c = files.getJSONObject(i);
String id = c.getString("id");
String url = c.getString("url");
//etc
//HERE IS WHAT YOU COULD DO OPTIONALLY IF YOU WANT HAVE IT ALL ON A SINGLE ARRAY WITHOUT OBJECTS:
ids[i] = id;
urls[i] = url;
//etc
}
this is a simple way to do this. see i also done this kind of string array and later use
try {
JSONObject jObj = new JSONObject(strDocketListResponse);
JSONArray jsonArray = jObj.getJSONArray("GetManifestDocketListResult");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject detailsObject = jsonArray.getJSONObject(i);
String strDktNo = detailsObject.getString("Docketno");
String strDocketDate = detailsObject.getString("DocketDate");
String strOrigin = detailsObject.getString("Origin");
String strDestination = detailsObject.getString("Destination");
String[] strDocketNoDkt = new String[]{strDktNo};
String[] strDocketDateDkt = new String[]{strDocketDate};
String[] strDocketOriginDkt = new String[]{strOrigin};
String[] strDocketDestnDkt = new String[]{strDestination};
for (int sanjay = 0; sanjay < strDocketNoDkt.length; sanjay++) {
ItemCheckList itemCheckList = new ItemCheckList();
itemCheckList.setDocket_NO(strDocketNoDkt[sanjay]);
itemCheckList.setDocket_Date(strDocketDateDkt[sanjay]);
itemCheckList.setDocket_Origin(strDocketOriginDkt[sanjay]);
itemCheckList.setDocket_Destination(strDocketDestnDkt[sanjay]);
checkLists.add(itemCheckList);
}
checkAdapter = new ItemCheckAdapter(ActivityManifestEntry.this, checkLists, check_all);
manifestListView.setAdapter(checkAdapter);
}
} catch (Exception e) {
e.printStackTrace();
}

Get value from JSONArray

JSONObject obj looks like this:
{"data":"Text 1","data2":"Text 2","turnCounter":0,"data3":["0","1","2"]}
I have been able to retrieve data, data2, and turnCounter but I can't figure out how to get data3:
Here is my attempt
JSONObject obj = new JSONObject(st);
if (obj.has("data")) {
retVal.data = obj.getString("data"); //returns Text 1
}
if (obj.has("data2")) {
retVal.data2 = obj.getString("data2"); //returns Text 2
}
if (obj.has("turnCounter")) {
retVal.turnCounter = obj.getInt("turnCounter"); // returns 0
}
List<String> allNames = new ArrayList<String>();
JSONArray cast = obj.getJSONArray("data3");
for (int i=0; i<cast.length(); i++) { //does not return 0, 1, or 2
JSONObject data3 = cast.getJSONObject(i); //"" "" ""
retVal.data3.set(i, data3.toString()); //"" "" ""
}
Can someone please tell me how I can get the value from the JsonArray data3?
Please let me know if I need to provide more information.
The way to do it is:
JSONArray cast = obj.getJSONArray("data3");
String[] string_array = new String[]();
for (int i=0; i<cast.length(); i++) {
string_array[i] = cast.getString(i);
retVal.data3.set(i, string_array[i]);
}
Try this. This will work.
change
JSONObject data3 = cast.getJSONObject(i); //
to
String data3 = cast.getString(i);
The array contains strings so you should call getString(i) instead of getObject(i):
JSONArray cast = obj.getJSONArray("data3");
for (int i=0; i<cast.length(); i++) {
String data3 = cast.getString(i);
Log.e("TAG", data3);
}

Categories

Resources