How to iterate JSON data in Android [closed] - java

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
{ "gb": [
{
"omrid": "gis-n",
"status": 0,
"grupp": 1
},
{
"omrid": "gis-s",
"status": 0,
"grupp": 1
},
{
"omrid": "gis-c",
"status": 0,
"grupp": 1
},
{
"omrid": "gis-h",
"status": 0,
"grupp": 1
},
{
"omrid": "gis-g",
"status": 0,
"grupp": 1
},
{
"omrid": "hes",
"status": 0,
"grupp": 2
} ] }
This above is my JSON String (edited shorter because it became too long here).
I'm trying to find a way to be able to iterate each group and create a togglebutton with them.
So what I'm trying to do is create a togglebutton with the name stated in "omrid" with the on/off status of "status". The "grupp" is for future use eventually to sort the toggles into groups but not important now.
I have searched and searched about this and noone seems to have my specific JSON string composition and I'm a bit of a noob with JSON/Android SDK.

I would use JSONObject. THer is no difference where you run in on Android or PC.
String str = "{" +
" \"gb\": [" +
" {" +
" \"omrid\": \"gis-n\"," +
" \"status\": 0," +
" \"grupp\": 1" +
" }," +
" {" +
" \"omrid\": \"gis-s\"," +
" \"status\": 0," +
" \"grupp\": 1" +
" }," +
" {" +
" \"omrid\": \"gis-c\"," +
" \"status\": 0," +
" \"grupp\": 1" +
" }," +
" {" +
" \"omrid\": \"gis-h\"," +
" \"status\": 0," +
" \"grupp\": 1" +
" }," +
" {" +
" \"omrid\": \"gis-g\"," +
" \"status\": 0," +
" \"grupp\": 1" +
" }," +
" {" +
" \"omrid\": \"hes\"," +
" \"status\": 0," +
" \"grupp\": 2" +
" }" +
" ]" +
"}";
JSONObject jsonObject = new JSONObject(str);
JSONArray gb = jsonObject.getJSONArray("gb");
for (int j = 0; j < gb.length(); j++) {
JSONObject element = gb.getJSONObject(j);
int status = element.getInt("status");
int grupp = element.getInt("grupp");
String omrid = element.getString("omrid");
System.out.println("status=" + status + "; grupp=" + grupp + "; omrid=" + omrid);
//create togglebutton here
}
Output:
status=0; grupp=1; omrid=gis-n
status=0; grupp=1; omrid=gis-s
status=0; grupp=1; omrid=gis-c
status=0; grupp=1; omrid=gis-h
status=0; grupp=1; omrid=gis-g
status=0; grupp=2; omrid=hes

here's the code
JSONObject json = new JSONObject(String your_json_string);
JSONArray arr = json.getJSONArray("gb");
for(int i = 0;i<arr.length();i++)
{
JSONObject temp = arr.getJSONObject(i);
temp.getString("omrid");//use them as your needs
temp.getString("status");//use them as your needs
temp.getString("grupp");// use them as your needs
}
Hope it helps.

Use following code to iterate.
Make one class JSONParser as below.
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONObject;
public class JSONParser {
public JSONParser() {
}
JSONObject jObj;
String json;
InputStream is = null;
public JSONObject getJsonFromUrl(String url) {
// TODO Auto-generated method stub
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (Exception e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
System.out.println("Json String : " + json);
} catch (Exception e) {
e.printStackTrace();
}
try {
jObj = new JSONObject(json);
} catch (Exception e) {
e.printStackTrace();
}
return jObj;
}
}
In your MainActivity use following to iterate.
JSONParser parser = new JSONParser();
JSONObject o = parser.getJsonFromUrl("yourjsonurl");
JSONArray array = o.getJSONArray("gb");
for (int i = 0; i < array.length(); i++){
JSONObject j = array.getJSONObject(i);
String omrid = j.getString("omrid");
String status= j.getString("status");
String grupp = j.getString("grupp");
}

Related

How to read multiple json objects using java?

I have a JSON response and I want to store each element in a string. as I am new to JSON, its difficult to find the solution. please suggest me a solution.
the below is my json response.
{
"responseFlag": 1,
"responseMsg": "Successfully retrieved data",
"responseObj": [{
"assets": {
"asset_since": "",
"asset_type": "",
"comments": "",
"estimated_value": "",
"material_status": "SINGLE",
"ownership_of_assets": "",
"pep": "",
"source_of_income": ""
}
},
{
"assets": {
"asset_since": "",
"asset_type": "",
"comments": "",
"estimated_value": "",
"material_status": "SINGLE",
"ownership_of_assets": "",
"pep": "",
"source_of_income": ""
}
}
]
}
I want to store each object elements in an array.
the code I have tried is below.
package mytry;
import java.util.Iterator;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
public class Mytry {
public static void main(String[] args) {
// TODO code application logic here
String response="{\n" +
" \"responseFlag\": 1,\n" +
" \"responseMsg\": \"Successfully retrieved data\",\n" +
" \"responseObj\": [\n" +
" {\n" +
" \"assets\": {\n" +
" \"asset_since\": \"\",\n" +
" \"asset_type\": \"\",\n" +
" \"comments\": \"\",\n" +
" \"estimated_value\": \"\",\n" +
" \"material_status\": \"SINGLE\",\n" +
" \"ownership_of_assets\": \"\",\n" +
" \"pep\": \"\",\n" +
" \"source_of_income\": \"\"\n" +
" }},\n" +
" {\n" +
" \"assets\": {\n" +
" \"asset_since\": \"\",\n" +
" \"asset_type\": \"\",\n" +
" \"comments\": \"\",\n" +
" \"estimated_value\": \"\",\n" +
" \"material_status\": \"SINGLE\",\n" +
" \"ownership_of_assets\": \"\",\n" +
" \"pep\": \"\",\n" +
" \"source_of_income\": \"\"\n" +
" }}]}";
JSONParser parser = new JSONParser();
try {
Object obj = parser.parse(response);
JSONObject jsonObject = (JSONObject) obj;
//System.out.println(jsonObject.toString());
System.out.println("json size=="+jsonObject.size());
System.out.println("hghgfh"+jsonObject.keySet());
Long sflag = (Long) jsonObject.get("responseFlag");
String msg=(String) jsonObject.get("responseMsg");
String resobj=(String) jsonObject.get("responseObj").toString();
//jsonObject.
System.out.println("sflag=="+sflag);
System.out.println("msg=="+msg);
System.out.println("msg=="+resobj);
// JSONArray msg = (JSONArray) jsonObject.get("responseFlag");
// Iterator<String> iterator = msg.iterator();
// while (iterator.hasNext()) {
// System.out.println(iterator.next());
// }
// for(Iterator iterator = jsonObject.keySet().iterator(); iterator.hasNext();) {
// String key = (String) iterator.next();
// System.out.println(jsonObject.get(key));
//}
// String asset = (String) jsonObject.get("assets");
// System.out.println("session token"+asset);
//sflag = (Long) jsonObject.get("responseFlag");
//System.out.println("session sflag"+sflag);
} catch (ParseException ex) {
System.out.println(ex);
}
}
}
the response object is
[{
"assets": {
"comments": "",
"asset_since": "",
"material_status": "SINGLE",
"source_of_income": "",
"ownership_of_assets": "",
"asset_type": "",
"pep": "",
"estimated_value": ""
}
}, {
"assets": {
"comments": "",
"asset_since": "",
"material_status": "SINGLE",
"source_of_income": "",
"ownership_of_assets": "",
"asset_type": "",
"pep": "",
"estimated_value": ""
}
}]
I need each asset values to be stored in an array.
Here is a pseudo code. You can fill the missing parts in this code.
String json = "{"responseFlag":1,"responseMsg":"Successfully retrieved data","responseObj":[{"assets":{"asset_since":"","asset_type":"","comments":"","estimated_value":"","material_status":"SINGLE","ownership_of_assets":"","pep":"","source_of_income":""}},{"assets":{"asset_since":"","asset_type":"","comments":"","estimated_value":"","material_status":"SINGLE","ownership_of_assets":"","pep":"","source_of_income":""}}]}";
JSONObject jsonObject = new JSONObject(json);
JSONArray jsonArray = jsonObject.getJSONArray("responseObj");
for(int i=0; i<jsonArray.length(); i++)
{
JSONObject arrayJsonObject = jsonArray.getJSONObject(i);
//insert into your list or array
}
If you are using using json-simple-1.1.1 jar. here is the code below:
JSONParser parser = new JSONParser();
try {
Object obj = parser.parse(response);
JSONObject jsonObject = (JSONObject) obj;
//System.out.println(jsonObject.toString());
System.out.println("json size==" + jsonObject.size());
System.out.println("hghgfh" + jsonObject.keySet());
JSONArray jsonArray = (JSONArray)jsonObject.get("responseObj");
for(int i=0; i<jsonArray.size(); i++)
{
JSONObject arrayJsonObject = (JSONObject) jsonArray.get(i);
JSONObject assets = (JSONObject) arrayJsonObject.get("assets");
// read the assets to store
}
}catch (Exception e){
}

Parsing JSON - null of type JSONObject cannot be converted to JSONArray

I'm trying to take the JSON from BITTREX and parse it and present it to the screen in Android Studio. This works for me with test JSON I made myself plus other requests i have made using the same API. However, when i go to use the actual request I need i get the following error :
JSONException: Value null of type org.json.JSONObject$1 cannot be converted to JSONArray
This is the request used: https://bittrex.com/api/v1.1/public/getmarketsummaries
API Documentation
Here is the Code :
public class fetchData extends AsyncTask<Void,Void,Void> {
String data=""; //all json lines after loop
String dataParsed ="";
String singleParsed =""; //parsed attributes
#Override
protected Void doInBackground(Void... voids) {
//Background Thread i.e API request
try {
URL url = new URL("https://bittrex.com/api/v1.1/public/getmarketsummaries\n");
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
InputStream inputStream = httpURLConnection.getInputStream(); //read data in from the connection
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream)); //Buff reader to read the inputstream (otherwise we get ints)
String line ="";
//Loop that reads all lines and represents them to as a string
while(line != null) {
line = bufferedReader.readLine(); //read line of json and assign to "line" if not null
data = data + line;
}
JSONArray myJsonArray = new JSONArray(data); //store json in a json array
for (int i = 0; i < myJsonArray.length(); i++) {
//Itterate through the array and get each object i.e btc,ltc
JSONObject myJsonObject = (JSONObject) myJsonArray.get(i);
//Single JSON object parsed
singleParsed = "Coin" + myJsonObject.get("MarketName") + "\n" +
"high" + myJsonObject.get("High") + "\n" +
"low" + myJsonObject.get("Low") + "\n" +
"volume" + myJsonObject.get("Volume") + "\n" +
"last" + myJsonObject.get("Last") + "\n" +
"basevolume" + myJsonObject.get("BaseVolume") + "\n" +
"time" + myJsonObject.get("Timestamp") + "\n" +
"bid" + myJsonObject.get("Bid") + "\n" +
"ask" + myJsonObject.get("Ask") + "\n" +
"openbuyorders" + myJsonObject.get("OpenBuyOrders") + "\n" +
"opensellorders" + myJsonObject.get("OpenSellOrders") + "\n" +
"prevday" + myJsonObject.get("PrevDay") + "\n" +
"created" + myJsonObject.get("Created") + "\n";
dataParsed = dataParsed + singleParsed + "\n";
}
}catch(MalformedURLException e ){
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
//UI thread
MainActivity.data.setText(this.dataParsed);
}
}
Any thoughts would be greatly appreciated. Thanks :)
**UPDATE - SOLVED **
I added the following line before the loop and it solved the issue.
//target the "result" Array of objects(BTC,LTC,ETH) and map them to a JsonArray for parsing
JSONArray myJsonArray = myJsonObj.getJSONArray("result");
The exception is perfectly valid. Your trying to convert json object into json array. Try below code
remove "\n" character at the end.
URL url = new URL("https://bittrex.com/api/v1.1/public/getmarketsummaries\n")
add below logs
while(line != null) {
line = bufferedReader.readLine(); //read line of json and assign to "line" if not null
data = data + line;
}
Log.debug("api_response","api-response->"+data);
and try below code
if(data!= null){ // add this if condition too.
JSONObject jsonObj = new JSONObject(data);
JSONArray myJsonArray = jsonObj.getJSONArray("result"); ; //store json in a json array
for (int i = 0; i < myJsonArray.length(); i++) {
//Itterate through the array and get each object i.e btc,ltc
JSONObject myJsonObject = (JSONObject) myJsonArray.get(i);
The json data returned by the API is in the following format:
{
"success": true,
"message": "",
"result": [
{
},
{
}
]
}
So you need to get the whole data as JSONObject first, then from it you can extract the JSONArray with the "result" key.
The code is something like this:
// get the JSONObject from the data
JSONObject jsonObject = new JSONObject(data);
// then you get the array with result key
JSONArray myJsonArray = jsonObject.getJSONArray("result");
for (int i = 0; i < myJsonArray.length(); i++) {
// now you can process the item here.
}
UPDATE
The above code is working. The remaining problem is there is a typo in your key. You're using "Timestamp" but the existing key is "TimeStamp". Here is the working code:
public class FetchData extends AsyncTask<Void,Void,Void> {
String data=""; //all json lines after loop
String dataParsed ="";
String singleParsed =""; //parsed attributes
#Override
protected Void doInBackground(Void... voids) {
//Background Thread i.e API request
try {
URL url = new URL("https://bittrex.com/api/v1.1/public/getmarketsummaries");
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
InputStream inputStream = httpURLConnection.getInputStream(); //read data in from the connection
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream)); //Buff reader to read the inputstream (otherwise we get ints)
String line ="";
//Loop that reads all lines and represents them to as a string
while(line != null) {
line = bufferedReader.readLine(); //read line of json and assign to "line" if not null
data = data + line;
Log.d("DATA", "line = " + line);
}
Log.d("DATA", "construct data = " + data);
JSONObject jsonObject = new JSONObject(data);
JSONArray myJsonArray = jsonObject.getJSONArray("result");
for (int i = 0; i < myJsonArray.length(); i++) {
//Itterate through the array and get each object i.e btc,ltc
JSONObject myJsonObject = (JSONObject) myJsonArray.get(i);
//Single JSON object parsed
singleParsed = "Coin" + myJsonObject.get("MarketName") + "\n" +
"high" + myJsonObject.get("High") + "\n" +
"low" + myJsonObject.get("Low") + "\n" +
"volume" + myJsonObject.get("Volume") + "\n" +
"last" + myJsonObject.get("Last") + "\n" +
"basevolume" + myJsonObject.get("BaseVolume") + "\n" +
"time" + myJsonObject.get("TimeStamp") + "\n" +
"bid" + myJsonObject.get("Bid") + "\n" +
"ask" + myJsonObject.get("Ask") + "\n" +
"openbuyorders" + myJsonObject.get("OpenBuyOrders") + "\n" +
"opensellorders" + myJsonObject.get("OpenSellOrders") + "\n" +
"prevday" + myJsonObject.get("PrevDay") + "\n" +
"created" + myJsonObject.get("Created") + "\n";
dataParsed = dataParsed + singleParsed + "\n";
}
}catch(MalformedURLException e ){
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
//UI thread
//MainActivity.data.setText(this.dataParsed);
Log.d("DATA", "data = " + this.dataParsed);
}
}

Extracting data from JSON and modifying data

I want to extract jkl object from below JSON string. Also after extraction, I want the backslashes to be removed and extract further with the braces. I followed few questions on StackOverflow but it didn't help much.
{
"abc:def": {
"ghi": {
"jkl": "{\"mno:pqr\":{\"ty\":4,\"\\nsensing_service_name:\\\"Number\\\",\\nsensing_service_id: 20\\n}\\n ]\\n}\"}}",
"st": {
"op": 5,
"org": "q9wr9qrq"
},
"uvw": 1
},
"xyz": false
}
}
I tried below code to display jkl object but it is not working. Please suggest what is wrong in this and how to correct the same
JSONObject json = (JSONObject) JSONSerializer.toJSON(data);
JSONObject aa = json.getJSONObject("abc:def");
JSONObject bb = aa.getJSONObject("ghi");
JSONObject cc = bb.getJSONObject("jkl");
System.out.println(cc);
Hope this will help you:
import org.apache.commons.lang3.StringUtils;
import org.json.JSONObject;
public class TestClass {
public static void main(String[] args) throws Exception {
String jsonString = "{\n" +
" \"abc:def\": {\n" +
" \"ghi\": {\n" +
" \"jkl\": \"{\\\"mno:pqr\\\":{\\\"ty\\\":4,\\\"\\\\nsensing_service_name:\\\\\\\"Number\\\\\\\",\\\\nsensing_service_id: 20\\\\n}\\\\n ]\\\\n}\\\"}}\",\n" +
" \"st\": {\n" +
" \"op\": 5,\n" +
" \"org\": \"q9wr9qrq\"\n" +
" },\n" +
" \"uvw\": 1\n" +
" },\n" +
" \"xyz\": false\n" +
" }\n" +
"} ";
JSONObject jsonObject = new JSONObject(jsonString);
jsonObject = (JSONObject) jsonObject.get("abc:def");
jsonObject = (JSONObject) jsonObject.get("ghi");
String result = jsonObject.getString("jkl");
result = StringUtils.replace(result, "\\n", "");
System.out.println(result.replaceAll("\\\\",""));
}
}

Traverse JSON data in JAVA

I am new to JSON..Am using HTTPUrlConnections and getting some response in JAVA program.The response data will be like,
{
"data": [
{
"id": 1,
"userId": 1,
"name": "ABC",
"modified": "2014-12-04",
"created": "2014-12-04",
"items": [
{
"email": "abc#gmail.com",
"links": [
{
.
.
.
.
}
]
}
]
}
]
}
From this response am able to get the value of "name" field with the below java code.
JSONArray items = newObj.getJSONArray("data");
for (int it=0 ; it < items.length() ; it++){
JSONObject contactItem = items.getJSONObject(it);
String userName = contactItem.getString("name");
System.out.println("Name----------"+userName);
}
But my requirement is,I need to get the value of "email" ..How should I code for that..
Any advice..
Thanks in advance..
Chitra
You need to first get the items array and each entry of this array contains JSONObject, from which you can call getString("email") .E.g.
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class App
{
public static void main( String[] args ) throws JSONException {
JSONObject newObj = new JSONObject("{" +
"\"data\": [\n" +
" {\n" +
"\"id\": 1,\n" +
" \"userId\": 1,\n" +
" \"name\": \"ABC\",\n" +
" \"modified\": \"2014-12-04\",\n" +
" \"created\": \"2014-12-04\",\n" +
" \"items\": [\n" +
" {\n" +
" \"email\": \"abc#gmail.com\",\n" +
" \"links\": [\n" +
" {\n" +
" }\n" +
" ]\n" +
" }\n" +
" ]\n" +
" }\n" +
" ]\n" +
"\n" +
"}");
JSONArray items = newObj.getJSONArray("data");
for (int it = 0; it < items.length(); it++) {
JSONObject contactItem = items.getJSONObject(it);
String userName = contactItem.getString("name");
JSONArray item = contactItem.getJSONArray("items");
for (int i = 0; i < items.length(); i++) {
String email = item.getJSONObject(i).getString("email");
System.out.println(email);
}
System.out.println("Name----------" + userName);
}
}
}
Output
abc#gmail.com
Name----------ABC
Extending your logic only:
JSONArray items = newObj.getJSONArray("data");
for (int it=0 ; it < items.length() ; it++){
JSONObject contactItem = items.getJSONObject(it);
String userName = contactItem.getString("name");
System.out.println("Name----------"+userName);
JSONArray itemsArr = contactItem.getJSONArray("items");
for (int item=0 ; item < itemsArr.length() ; item++){
String email = item.getString("email");
System.out.println("Email----------"+email);
}
}
This should work, with few tweaks. I have not actually tested it, just writing freehand here.
You can also use Jackson library from FasterXML. You can convert the JSON String into Java object very easily and then you can traverse using iterations on Collections.
If you look the JSON String it contains items which can be considered as an Array within an Array, so in order to get the value of email all you need to do is to create another JSONArray like:
JSONArray itemsArray = contactItem.getJSONArray("items");
Then you can retrieve the value of email over this Array
Thank you so much for your time and response.
The below code did the magic:
JSONArray responseContactData = responseContact.getJSONArray("data");
for (int i=0; i < responseContactData.length(); i++) {
String emails = contactDataValues.getJSONArray("items").getJSONObject(0).getString("email");
}

Parsing JSON string in Java

I am trying to parse a JSON string in java to have the individual value printed separately. But while making the program run I get the following error-
Exception in thread "main" java.lang.RuntimeException: Stub!
at org.json.JSONObject.<init>(JSONObject.java:7)
at ShowActivity.main(ShowActivity.java:29)
My Class looks like-
import org.json.JSONException;
import org.json.JSONObject;
public class ShowActivity {
private final static String jString = "{"
+ " \"geodata\": ["
+ " {"
+ " \"id\": \"1\","
+ " \"name\": \"Julie Sherman\","
+ " \"gender\" : \"female\","
+ " \"latitude\" : \"37.33774833333334\","
+ " \"longitude\" : \"-121.88670166666667\""
+ " }"
+ " },"
+ " {"
+ " \"id\": \"2\","
+ " \"name\": \"Johnny Depp\","
+ " \"gender\" : \"male\","
+ " \"latitude\" : \"37.336453\","
+ " \"longitude\" : \"-121.884985\""
+ " }"
+ " }"
+ " ]"
+ "}";
private static JSONObject jObject = null;
public static void main(String[] args) throws JSONException {
jObject = new JSONObject(jString);
JSONObject geoObject = jObject.getJSONObject("geodata");
String geoId = geoObject.getString("id");
System.out.println(geoId);
String name = geoObject.getString("name");
System.out.println(name);
String gender=geoObject.getString("gender");
System.out.println(gender);
String lat=geoObject.getString("latitude");
System.out.println(lat);
String longit =geoObject.getString("longitude");
System.out.println(longit);
}
}
Let me know what is it I am missing, or the reason why I do get that error everytime I run the application. Any comments would be appreciated.
See my comment.
You need to include the full org.json library when running as android.jar only contains stubs to compile against.
In addition, you must remove the two instances of extra } in your JSON data following longitude.
private final static String JSON_DATA =
"{"
+ " \"geodata\": ["
+ " {"
+ " \"id\": \"1\","
+ " \"name\": \"Julie Sherman\","
+ " \"gender\" : \"female\","
+ " \"latitude\" : \"37.33774833333334\","
+ " \"longitude\" : \"-121.88670166666667\""
+ " },"
+ " {"
+ " \"id\": \"2\","
+ " \"name\": \"Johnny Depp\","
+ " \"gender\" : \"male\","
+ " \"latitude\" : \"37.336453\","
+ " \"longitude\" : \"-121.884985\""
+ " }"
+ " ]"
+ "}";
Apart from that, geodata is in fact not a JSONObject but a JSONArray.
Here is the fully working and tested corrected code:
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class ShowActivity {
private final static String JSON_DATA =
"{"
+ " \"geodata\": ["
+ " {"
+ " \"id\": \"1\","
+ " \"name\": \"Julie Sherman\","
+ " \"gender\" : \"female\","
+ " \"latitude\" : \"37.33774833333334\","
+ " \"longitude\" : \"-121.88670166666667\""
+ " },"
+ " {"
+ " \"id\": \"2\","
+ " \"name\": \"Johnny Depp\","
+ " \"gender\" : \"male\","
+ " \"latitude\" : \"37.336453\","
+ " \"longitude\" : \"-121.884985\""
+ " }"
+ " ]"
+ "}";
public static void main(final String[] argv) throws JSONException {
final JSONObject obj = new JSONObject(JSON_DATA);
final JSONArray geodata = obj.getJSONArray("geodata");
final int n = geodata.length();
for (int i = 0; i < n; ++i) {
final JSONObject person = geodata.getJSONObject(i);
System.out.println(person.getInt("id"));
System.out.println(person.getString("name"));
System.out.println(person.getString("gender"));
System.out.println(person.getDouble("latitude"));
System.out.println(person.getDouble("longitude"));
}
}
}
Here's the output:
C:\dev\scrap>java -cp json.jar;. ShowActivity
1
Julie Sherman
female
37.33774833333334
-121.88670166666667
2
Johnny Depp
male
37.336453
-121.884985
To convert your JSON string to hashmap you can make use of this :
HashMap<String, Object> hashMap = new HashMap<>(Utility.jsonToMap(response)) ;
Use this class :) (handles even lists , nested lists and json)
public class Utility {
public static Map<String, Object> jsonToMap(Object json) throws JSONException {
if(json instanceof JSONObject)
return _jsonToMap_((JSONObject)json) ;
else if (json instanceof String)
{
JSONObject jsonObject = new JSONObject((String)json) ;
return _jsonToMap_(jsonObject) ;
}
return null ;
}
private static Map<String, Object> _jsonToMap_(JSONObject json) throws JSONException {
Map<String, Object> retMap = new HashMap<String, Object>();
if(json != JSONObject.NULL) {
retMap = toMap(json);
}
return retMap;
}
private static Map<String, Object> toMap(JSONObject object) throws JSONException {
Map<String, Object> map = new HashMap<String, Object>();
Iterator<String> keysItr = object.keys();
while(keysItr.hasNext()) {
String key = keysItr.next();
Object value = object.get(key);
if(value instanceof JSONArray) {
value = toList((JSONArray) value);
}
else if(value instanceof JSONObject) {
value = toMap((JSONObject) value);
}
map.put(key, value);
}
return map;
}
public static List<Object> toList(JSONArray array) throws JSONException {
List<Object> list = new ArrayList<Object>();
for(int i = 0; i < array.length(); i++) {
Object value = array.get(i);
if(value instanceof JSONArray) {
value = toList((JSONArray) value);
}
else if(value instanceof JSONObject) {
value = toMap((JSONObject) value);
}
list.add(value);
}
return list;
}
}
credit to this blog
This answer may help someone whose requirements are different.
This is your Json string
{
"pageNumber":20,
"pageTitle":"example page title",
"pageInfo": {
"pageName": "Homepage",
"logo": "https://www.example.com/logo.jpg"
},
"posts": [
{
"post_id": "0123456789",
"actor_id": "1001",
"author_name": "Jane Doe",
"post_title": "How to parse JSON in Java",
"comments": [],
"time_of_post": "1234567890"
}
]
}
and this is how to read it
import org.json.JSONArray;
import org.json.JSONObject;
public class ParseJSON {
static String json = "...";
public static void main(String[] args) {
JSONObject obj = new JSONObject(json);
String pageTitle = obj.getString("pageTitle");
String pageNumber= obj.getInt("pageNumber");
String pageName = obj.getJSONObject("pageInfo").getString("pageName");
System.out.println(pageNumber);
System.out.println(pageTitle );
System.out.println(pageName);
JSONArray arr = obj.getJSONArray("posts");
for (int i = 0; i < arr.length(); i++) {
String post_id = arr.getJSONObject(i).getString("post_id");
System.out.println(post_id);
}
}
}
Looks like for both of your objects (inside the array), you have an extra closing brace after "Longitude".
Firstly there is an extra } after every array object.
Secondly "geodata" is a JSONArray. So instead of JSONObject geoObject = jObject.getJSONObject("geodata"); you have to get it as JSONArray geoObject = jObject.getJSONArray("geodata");
Once you have the JSONArray you can fetch each entry in the JSONArray using geoObject.get(<index>).
I am using org.codehaus.jettison.json.
Here is the example of one Object, For your case you have to use JSONArray.
public static final String JSON_STRING="{\"employee\":{\"name\":\"Sachin\",\"salary\":56000}}";
try{
JSONObject emp=(new JSONObject(JSON_STRING)).getJSONObject("employee");
String empname=emp.getString("name");
int empsalary=emp.getInt("salary");
String str="Employee Name:"+empname+"\n"+"Employee Salary:"+empsalary;
textView1.setText(str);
}catch (Exception e) {e.printStackTrace();}
//Do when JSON has problem.
}
I don't have time but tried to give an idea. If you still can't do it, then I will help.
you have an extra "}" in each object,
you may write the json string like this:
public class ShowActivity {
private final static String jString = "{"
+ " \"geodata\": ["
+ " {"
+ " \"id\": \"1\","
+ " \"name\": \"Julie Sherman\","
+ " \"gender\" : \"female\","
+ " \"latitude\" : \"37.33774833333334\","
+ " \"longitude\" : \"-121.88670166666667\""
+ " }"
+ " },"
+ " {"
+ " \"id\": \"2\","
+ " \"name\": \"Johnny Depp\","
+ " \"gender\" : \"male\","
+ " \"latitude\" : \"37.336453\","
+ " \"longitude\" : \"-121.884985\""
+ " }"
+ " }"
+ " ]"
+ "}";
}

Categories