How to parse JSON array into an Android list [duplicate] - java

This question already has answers here:
JSON parsing using Gson for Java
(11 answers)
How do I parse JSON in Android? [duplicate]
(3 answers)
How to parse JSON in Java
(36 answers)
Sending and Parsing JSON Objects in Android [closed]
(11 answers)
How to Parse a JSON Object In Android
(4 answers)
Closed 2 years ago.
I have a rather specific question about JSON parsing in Android.
I have a requirement to download a single JSON array containing information in the format shown below, the number of JSON objects in the array is variable. I need to retrieve all the JSON values in the array so each JSON value has to be stored as an android list named after the common JSON keys because there are many instances of each, e.g. a list for placenames keys [place1,place2,place3 = placename list], a list for questions key, etc. A caveat to this is I cannot use an android array to store these JSON key values since each time my app runs this download task I don't know how many JSON objects will be in the single array. Users can submit as much as they want at any time to the database.
[
{
"placename": "place1",
"latitude": "50",
"longitude": "-0.5",
"question": "place1 existed when?",
"answer1": "1800",
"answer2": "1900",
"answer3": "1950",
"answer4": "2000",
"correctanswer": "1900"
},
{
"placename": "place2",
"latitude": "51",
"longitude": "-0.5",
"question": "place2 existed when?",
"answer1": "800",
"answer2": "1000",
"answer3": "1200",
"answer4": "1400",
"correctanswer": "800"
},
{
"placename": "place3",
"latitude": "52",
"longitude": "-1",
"question": "place 3 was established when?",
"answer1": "2001",
"answer2": "2005",
"answer3": "2007",
"answer4": "2009",
"correctanswer": "2009"
}
]
Below is my code for mainactivity which I managed to get working but had a derp moment and realised I'd simply gone through and parsed out the values for each JSON key in each object as a single string value for each JSON key. Since the loop iterates it merely overwrites at each stage - the placename string is "place1", then "place2", then "place3" by the end of the loop, rather than ["place1","place2", "place3"] which is what I want. My question now is how would I go about parsing the JSONArray to extract all instances of each JSON value and output as a string list for each JSON key, the length of the list is determined by the number of Objects?
I've already got the template for a string list that stores all the JSON key values (commented out in the below code) but I'm not sure how to fill that String list from the JSON parsing process.
I've had a good look around and couldn't find anything specifically about JSON Array to Android List so help would be greatly appreciated. I'd also like to know if there is a way of maintaining association between each list (e.g. questions & answers for specific placenames) if I bundle the data out to different activities (e.g. q&a to a quiz and placenames/lat/lon to GPS). Can I do this by referencing the same index in the list? Or would I need to store these lists in local storage? an SQL lite database?
Thanks for your time and sorry for the overwhelmingly long post!
public class MainActivity extends Activity {
// The JSON REST Service I will pull from
static String dlquiz = "http://www.example.php";
// Will hold the values I pull from the JSON
//static List<String> placename = new ArrayList<String>();
static String placename = "";
static String latitude = "";
static String longitude = "";
static String question = "";
static String answer1 = "";
static String answer2 = "";
static String answer3 = "";
static String answer4 = "";
static String correctanswer = "";
#Override
public void onCreate(Bundle savedInstanceState) {
// Get any saved data
super.onCreate(savedInstanceState);
// Point to the name for the layout xml file used
setContentView(R.layout.main);
// Call for doInBackground() in MyAsyncTask to be executed
new MyAsyncTask().execute();
}
// Use AsyncTask if you need to perform background tasks, but also need
// to change components on the GUI. Put the background operations in
// doInBackground. Put the GUI manipulation code in onPostExecute
private class MyAsyncTask extends AsyncTask<String, String, String> {
protected String doInBackground(String... arg0) {
// HTTP Client that supports streaming uploads and downloads
DefaultHttpClient httpclient = new DefaultHttpClient(new BasicHttpParams());
// Define that I want to use the POST method to grab data from
// the provided URL
HttpPost httppost = new HttpPost(dlquiz);
// Web service used is defined
httppost.setHeader("Content-type", "application/json");
// Used to read data from the URL
InputStream inputStream = null;
// Will hold the whole all the data gathered from the URL
String result = null;
try {
// Get a response if any from the web service
HttpResponse response = httpclient.execute(httppost);
// The content from the requested URL along with headers, etc.
HttpEntity entity = response.getEntity();
// Get the main content from the URL
inputStream = entity.getContent();
// JSON is UTF-8 by default
// BufferedReader reads data from the InputStream until the Buffer is full
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
// Will store the data
StringBuilder theStringBuilder = new StringBuilder();
String line = null;
// Read in the data from the Buffer untilnothing is left
while ((line = reader.readLine()) != null)
{
// Add data from the buffer to the StringBuilder
theStringBuilder.append(line + "\n");
}
// Store the complete data in result
result = theStringBuilder.toString();
} catch (Exception e) {
e.printStackTrace();
}
finally {
// Close the InputStream when you're done with it
try{if(inputStream != null)inputStream.close();}
catch(Exception e){}
}
//Log.v("JSONParser RESULT ", result);
try {
JSONArray array = new JSONArray(result);
for(int i = 0; i < array.length(); i++)
{
JSONObject obj = array.getJSONObject(i);
//now, get whatever value you need from the object:
placename = obj.getString("placename");
latitude = obj.getString("latitude");
longitude = obj.getString("longitude");
question = obj.getString("question");
answer1 = obj.getString("answer1");
answer2 = obj.getString("answer2");
answer3 = obj.getString("answer3");
answer4 = obj.getString("answer4");
correctanswer = obj.getString("correctanswer");
}
} catch (JSONException e){
e.printStackTrace();
}
return result;
}
protected void onPostExecute(String result){
// Gain access so I can change the TextViews
TextView line1 = (TextView)findViewById(R.id.line1);
TextView line2 = (TextView)findViewById(R.id.line2);
TextView line3 = (TextView)findViewById(R.id.line3);
// Change the values for all the TextViews
line1.setText("Place Name: " + placename);
line2.setText("Question: " + question);
line3.setText("Correct Answer: " + correctanswer);
}
}
}

Instead of keeping variables:
static String placename = "";
static String latitude = "";
static String longitude = "";
static String question = "";
static String answer1 = "";
static String answer2 = "";
static String answer3 = "";
static String answer4 = "";
static String correctanswer = "";
make Bean Class having all these variables. Make array list of bean and during parsing make bean objects and add to list.
Bean Class:
public class ModelClass{
private String latitude = "";
private String longitude = "";
private String question = "";
private String answer1 = "";
private String answer2 = "";
private String answer3 = "";
private String answer4 = "";
private String correctanswer = "";
// ....
// Getter Setters and constructors
// .......
}
ArrayList<ModelClass> mList=new ArrayList<ModelClass>();
In for loop of json parsing:
JSONObject obj = array.getJSONObject(i);
ModelObject object=new ModelObject();
// parse and make ModelObject
list.add(object);
Try using this approach. It will work.

you should divide your objects into classes, and use the GSON json parser.
look at this answer on how to parse a json array into objects:
JSON parsing using Gson for Java
a good approach would be a class question that contains a list of subclasses called possibleanswers, those have a boolean attribute ( correct : true, incorrect: false) to check if the user has clicked the correct one.
if you want to store the data, you will have to use sqllite or any of the many libraries like ActiveAndroid.

I see that you are accessing this JSON file form a Remote Service. On that basis, you will need to structure your code in a manner that will work around how many instances are in the physical JSON file.
Your issue is here:
JSONArray array = new JSONArray(result);
for(int i = 0; i < array.length(); i++)
{
JSONObject obj = array.getJSONObject(i);
You are telling it that the entire JSON file has an array, which contains a length, which is incorrect.
Curly Brackets ("{") represent a JSONObject, and Square Brackets ("[") represent a JSON Array.
Based on your JSON file:
[
{
"placename": "place1",
"latitude": "50",
"longitude": "-0.5",
"question": "place1 existed when?",
"answer1": "1800",
"answer2": "1900",
"answer3": "1950",
"answer4": "2000",
"correctanswer": "1900"
},
You are dealing with one JSONArray, and this array has to no reference name give to it, rather a place index.
Heres what you need to try:
public class ListCreator{
private List<String> placename;
public ListCreator() {
placename = new ArrayList<String>();
}
public void addPlaceName(String s)
{
answers.add(s);
}
public String[] getAnswers()
{
return placename.toArray(new String[1]);
}
}
Bear in mind that is just a snippet of what the class will look like only for the "placename" fields.
Now to your JSON:
You will need to initialize a Vector Variable for each List you want to create:
private Vector<ListCreator> placeNameVec;
Next you will need to set a method for each part of the JSONArray:
public Vector getPlaceNames(){
return placeNameVector;
}
JSONArray array = new JSONArray(result);
for(int x = 0; x < 3; x++){
JSONObject thisSet = array.getJSONObject(x);
ListCreator placeNames = new ListCreator();
placeNames.addPlaceName(thisSet.getString("placename"));
}
placeNameVec.add(placeNames);
That should get you going on what you are trying to answer.
So basically bear in mind that you you can't specify the "array.length()".
Hope this helps!
Please let me know of the outcome :)
If you get into any further difficulty, this Tutorial on JSONParsing really did help me when I was confused.
All the best

Related

How to convert this json String to normal java arraylist using gson

I tried to convert following JSON string into Array and got following error:
Exception in thread "AWT-EventQueue-0" java.lang.NoClassDefFoundError:
org/apache/commons/logging/LogFactory at
net.sf.json.AbstractJSON.(AbstractJSON.java:54) at
net.sf.json.util.CycleDetectionStrategy.(CycleDetect‌​ionStrategy.java:36)
at net.sf.json.JsonConfig.(JsonConfig.java:65) at
net.sf.json.JSONSerializer.toJSON(JSONSerializer.java:84)
JSON:
[
{
"file_name":"1.xml",
"file_ext":"application/octet-stream",
"sr_no":"0.1",
"status":"Checked ",
"rev":"1",
"locking":"0"
},
{
"file_name":"2.xml",
"file_ext":"json/octet-stream",
"sr_no":"0.2",
"status":"Not Checked ",
"rev":"2",
"locking":"1"
},
{
"file_name":"3.xml",
"file_ext":"application/json-stream",
"sr_no":"0.3",
"status":"Checked ",
"rev":"1",
"locking":"3"
},
{
"file_name":"4.xml",
"file_ext":"application/octet-stream",
"sr_no":"0.4",
"status":"Checked ",
"rev":"0.4",
"locking":"4"
}
]
Code:
JSONArray nameArray = (JSONArray) JSONSerializer.toJSON(output);
System.out.println(nameArray.size());
for(Object js : nameArray)
{
JSONObject json = (JSONObject) js;
System.out.println("File_Name :" +json.get("file_name"));
}
I know the question is about converting JSON String to Java Array, but I would like to also answer about how to convert the JSON String to an ArrayList using the Gson Library.
Since I spend a good amount of time in solving this, I hope my solution may help others.
My JSON string looks similar to this one -
I had an object named StockHistory, and I wanted to convert this JSON into an ArrayList of StockHistory.
This is how my StockHistory class looked -
class StockHistory {
Date date;
Double open;
Double high;
Double low;
Double close;
Double adjClose;
Double volume;
}
The code that I used to convert the JSON Array to the ArrayList of StockHistory is as follows -
Gson gson = new Gson();
Type listType = new TypeToken< ArrayList<StockHistory> >(){}.getType();
List<StockHistory> history = gson.fromJson(reader, listType);
Now if you are reading your JSON from a file, the reader's initialization would be -
Reader reader = new FileReader(fileName);
and if you are just converting a string to JSON object then, the reader's initialization would simply be -
String reader = "{ // json String }";
Hope that helps. Cheers!!!
You can create a java class with entities are: file_name, file_ext, sr_no, status, rev, locking in string type.
public class TestJson {
private String file_name, file_ext, sr_no, status, rev, locking;
//get & set
}
}
Then you call:
public static void main(String[] args) {
String json = your json string;
TestJson[] respone = new Gson().fromJson(json, TestJson[].class);
for (TestJson s : respone) {
System.out.println("File name: " + s.getFile_name());
}
}
So, you have a list of object you want.
Firstly I have to say your question is quite "ugly" and next time please improve your question's quality.
Answer:
Try to use com.fasterxml.jackson.databind.ObjectMapper
If you have a java class to describe your items in the list:
final ObjectMapper mapper = new ObjectMapper();
YourClass[] yourClasses = mapper.readValue(YourString, YourClass[].class);
Then convert the array to a List.
If you don't have a java class, just you LinkedHashMap instead.

JSONObject parse dictionary objects

JSON values that I get from server:
{
"Status":0,
"Message":"",
"Result":{"0B":"S.C. Blue Air","0Y":"FlyYeti","1X":"Branson Air"}
}
Getting the result as 'response' after connection and I am able to show my JSON string results on the screen.
JSONObject json = new JSONObject(response);
String status = json.getString("Status");
String message = json.getString("Message");
String result = json.getString("Result");
responseView.setText("Status" + status+ "Message" + message" + Result" + result);
I am okay the results of "Status" and "Message" but not with "Result" because want to separate "Result" objects as and able use each of them as objects.
For example:
When I type OB in my app, I will get the result S.C. Blue Air
Instead of :
String result = json.getString("Result");
use
if(json.get("Result") instanceof JSONObject){
JSONObject object = (JSONObject) json.get("Result");
//do what you want with JSONObject
String ob = object.get("0B");
}
If you want to store it some way you can put it to Map or create object if always it is same data
You can use some libraries such as Gson (Google) or Moshi (Square)
Those libraries allows you to declare your model as a plain java class (commonly called POJOS) annotated in some way that this libraries bind your properties in the JSON to your java properties.
In your case:
JSON:
{
"Status":0,
"Message":"",
"Result":{"0B":"S.C. Blue Air","0Y":"FlyYeti","1X":"Branson Air"}
}
MODEL:
public class MyCallResponse {
#SerializedName("Status")
int status;
#SerializedName("Message")
String message;
#SerializedName("Result")
Result result;
}
public class Result {
#SerializedName("0B")
String b;
#SerializedName("0Y")
String y;
#SerializedName("0X")
String x;
}
In this case, with Gson you can do:
MyCallResponse response = new Gson().fromJson(json, MyCallResponse.class);
Log.i("Response b", response.result.b);
Look at the documentation for more information about both libraries.
try this :
JSONObject json = new JSONObject(response);
JSONObject resultObj = json.getJSONObject("Result");
String OB = resultObj.getString("OB");
Try this
String base = ""; //Your json string;
JSONObject json = new JSONObject(base);
JSONOBject resultJson = json.getJSONObject("Result");
// Get all json keys "OB", "OY", "1X" etc in Result, so that we can get values against each key.
Set<Map.Entry<String, JsonElement>> entrySet = resultJson.entrySet();
Iterator iterator = entrySet.iterator();
for (int j = 0; j < entrySet.size(); j++) {
String key = null; //key = "OB", "OY", "1X" etc
try {
Map.Entry entry = (Map.Entry) iterator.next ();
key = entry.getKey ().toString ();
//key = "OB", "OY", "1X" etc
}
catch (NoSuchElementException e) {
e.printStackTrace ();
}
if (!TextUtils.isEmpty (key)) {
Log.d ("JSON_KEY", key);
String value = resultJson.getString(key);
//for key = "0B", value = "S.C. Blue Air"
//for key = "0Y", value = "FlyYeti"
//for key = "1X", value = "Branson Air"
}
}
It works with any array with dynamic json key.
Don't forget to accept the answer & upvote if it works.

How to get specific JSON data?

Hi I am trying to read JSON from an ReST API but Im getting a nullpointer exception because mycode is not correct.
I have a JSON that I am reading from looking like this :
processJSON({
"LocationList":{
"noNamespaceSchemaLocation":"http://api.vasttrafik.se/v1/hafasRestLocation.xsd",
"servertime":"16:13",
"serverdate":"2013-03-22",
"StopLocation":[{
"name":"Brunnsparken, Göteborg",
"lon":"11.967824",
"lat":"57.706944",
"id":"9021014001760000",
"idx":"1"
},{
"name":"Brunnsgatan, Göteborg",
"lon":"11.959455",
"lat":"57.693766",
"id":"9021014001745000",
"idx":"4"
},{
"name":"Brunnslyckan, Lerum",
"lon":"12.410219",
"lat":"57.812073",
"id":"9021014017260000",
"idx":"5"
},
Now I want the name from the JSON document depending on what the user inputs.
how do I do this with code?
My code that is wrong is like this :
import org.json.simple.JSONObject;
import org.json.simple.JSONValue;
public class JSONReader {
private String jsonData = "";
public String getJsonData(String location){
try {
URL url = new URL("http://api.vasttrafik.se/bin/rest.exe/v1/location.name?authKey=secret&format=json&jsonpCallback=processJSON&input=" + URLEncoder.encode(location, "UTF-8"));
URLConnection connection = url.openConnection();
BufferedReader readJsonFile = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
String temp = "";
while((temp = readJsonFile.readLine()) != null){
jsonData += temp;
}
readJsonFile.close();
System.out.println(jsonData);
return jsonData;
}
catch (IOException e) {
}
return null;
}
public void JSONParsing(){
String location = Planner.getPlanner().getStartingLocation();
JSONObject obj =(JSONObject)JSONValue.parse(getJsonData(location));
//Set the text into the JList
if (obj.containsValue(location));
obj.get("name");
}
}
I want get the same name of the location out from the JSON as the user inputs.
How do I do this with code?
I think that you are asking how to parse your JSONObject and get the corresponding values out of it that the user is interested in. Below is an example of how you can pull apart the JSONObject to create a Map whose key is the String id (since the name does not seem to be unique) and whose value is the whole JSONObject. You can use this map to lookup the input from the user and find the appropriate LLA if that's what you are interested in.
public Map<String, JSONObject> createLocationMap(JSONObject jsonObj){
Map<String, JSONObject> nameToLocationMap = new HashMap<String, JSONObject>();
JSONObject locationList = (JSONObject) jsonObj.get("LocationList");
JSONArray array = (JSONArray) locationList.get("StopLocation");
for (int i = 0; i < array.length(); i++) {
String name = (String) ((JSONObject) array.get(i)).get("id");
nameToLocationMap.put(name, ((JSONObject)array.get(i)));
}
return nameToLocationMap;
}
You can tailor this method as you see fit. For example if you are interested in the relationship between the id and the name then you can create a similar method that uses those values instead of id and the entire JSONObject'. I hope that this helps~

What should I do to solve this error?

I was using JSONParser to obtain results of a search, for that I followed this tutorial: http://www.androidhive.info/2012/01/android-json-parsing-tutorial/
The thing is that, the API I am using gives the results like this:
{"response":[50036,{"aid":88131498,"owner_id":61775052,"artist":"Terror Squad","title":"Lean Back (OST Need For Speed Underground 2)","duration":249,"url":"http:\/\/cs4408.vkontakte.ru\/u59557424\/audio\/7f70f58bb9b8.mp3","lyrics_id":"3620730"},{"aid":106963458,"owner_id":-24764574,"artist":"«Dr. Dre ft Eminem, Skylar Grey (Assault Terror)","title":"I Need A Doctor (ASSAULT TERROR DUBSTEP REMIX)»","duration":240,"url":"http:\/\/cs5101.vkontakte.ru\/u79237547\/audio\/12cd12c7f8c2.mp3","lyrics_id":"10876670"}]}
My problem comes when I have to parse the first integer (here it is 50036) which is the number of results found.
I don't know how to read that integer.
This is my code:
private void instance(String artisttrack){
// Creating JSON Parser instance
JSONParser jParser = new JSONParser();
// getting JSON string from URL
String jsonurl = new String( "https://api.vk.com/method/audio.search?access_token=ACC_TOKEN&api_id=ID&sig=SIG&v=2.0&q=" + artistname + artisttrack + "&count=5");
JSONObject json = jParser.getJSONFromUrl(jsonurl);
try {
// Getting Array of Contacts
response = json.getJSONArray(TAG_RESPONSE);
// looping through All Contacts
for(int i = 0; i < response.length(); i++){
JSONObject c = response.getJSONObject(i);
// Storing each json item in variable
//int results = Integer.parseInt(c.getString(TAG_RESULTS));
String aid = c.getString(TAG_AID);
String owner_id = c.getString(TAG_OWNER_ID);
String artist = c.getString(TAG_ARTIST);
String title = c.getString(TAG_TITLE);
String duration = c.getString(TAG_DURATION);
// Phone number is agin JSON Object
//JSONObject phone = c.getJSONObject(TAG_PHONE);
String url = c.getString(TAG_URL);
String lyrics_id = c.getString(TAG_LYRICS_ID);
Log.e("áaaaaaaaaaaaaaa", url);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
The JSONParser.java is like written in the tutorial.
And here 2 lines of the logcat error:
W/System.err(10350): org.json.JSONException: Value 50036 at 0 of type java.lang.Integer cannot be converted to JSONObject
W/System.err(10350): at org.json.JSON.typeMismatch(JSON.java:100)
Your JSON sample is a poor way to organize the results: mixing the number in with the result objects. Is the number supposed to indicate the number of objects in the array or something else?
If you can assume that this number will always be the first element, and according to this then it's supposed to work this way, you can try to read the first value of the array outside the loop:
response = json.getJSONArray(TAG_RESPONSE);
// from your example, num will be 50036:
num = response.getInt(0);
for (int i = 1; i < response.length(); i++){
JSONObject c = response.getJSONObject(i);
Note that the example in the linked documentation has this number as a string:
{"response":
["5",
{"aid":"60830458","owner_id":"6492","artist":"Noname","title":"Bosco",
"duration":"195","url":"http:\/\/cs40.vkontakte.ru\/u06492\/audio\/2ce49d2b88.mp3"},
{"aid":"59317035","owner_id":"6492","artist":"Mestre Barrao","title":"Sinhazinha",
"duration":"234","url":"http:\/\/cs510.vkontakte.ru\/u2082836\/audio\/
d100f76cb84e.mp3"}]}
But JSONArray.getInt() will parse the String as an int for you.
And notice that some of the values in the objects in your array are also numbers, you may want to read those as int also:
int aid = c.getInt(TAG_AID);
int owner_id = c.getInt(TAG_OWNER_ID);
int duration = c.getInt(TAG_DURATION);
A lot of the values you are trying to parse in are not String objects, specifically "aid", "owner_id", and "duration". Use the correct method to retrieve values. For example:
int aid = c.getInt(TAG_AID);
int owner_id = c.getInt(TAG_OWNER_ID);
String artist = c.getString(TAG_ARTIST);
String title = c.getString(TAG_TITLE);
int duration = c.getInt(TAG_DURATION);
edit: Another error that I missed is you start your array with 50036. This is not a JSONObject and cannot be parsed as so. You can add a conditional statement to check if it's array index 0 to parse the int using getInt(), and then parse as JSONObjects for the rest of the array values.
Try changing
response = json.getJSONArray(TAG_RESPONSE);
into
response = (JSONObject)json.getJSONArray(TAG_RESPONSE);
I dont have any experience with JSONObject, but works often with type mismatches.
Try putting 50036 in quotes like this "50036" .

Extract different values returned in json format using GET REST call

I am developing an application in which I am using GET REST call to get some specific nodes which return's me the nodes in the below json format:
[
{
"nodeId": "30",
"datasetId": "2",
"localId": "30",
"datasetName": "Optimal Travel Route",
"nodeName": "Location30",
"nodeDesc": "Find the optimal travel route using travelling salesman problem ",
"nodeStatus": "Private",
"gpsLat": "8.233240",
"gpsLong": "15.029300",
"addedBy": "internIITD",
"addedOn": "2012-06-29 11:08:28",
"updatedOn": "2012-06-29 11:08:28"
}
]
they are no newlines .I have added here to make it readable. I am doing this to convert it to string.:
BufferedReader in = new BufferedReader(new InputStreamReader(
httpCon.getInputStream()));
String inputLine;
StringBuilder sb = new StringBuilder();
while ((inputLine = in.readLine()) != null) {
sb.append(inputLine);
System.out.println(inputLine);
}
String Result;
Result=sb.toString();
System.out.println("result:"+Result);
I want to extract the longitude and latitude of the nodes that will be given meeting specific requirements. I am working in NetBeans 7.1.2 . I am new to JAVA.
So , can anyone tell is there any way to extract this latitude and longitde information and store it in integer varibles.
I used to declare JSONObject but it is not working here .I don't know why?I am not able to use JSONArray or JSONObect in my code. It is showing me an error.In the class in which I am doing this does not have a mail function. this class i.e. file has been called by some other .java file . I have multiple windows in my application.
Please help.
This would be a solution:
String jsonSource = /* your json string */;
JSONArray array = new JSONArray(jsonSource);
for (int i = 0; i < array.length(); i++) {
JSONObject firstObject = (JSONObject) array.get(i);
System.out.println("Lat is: " + firstObject.getDouble("gpsLat"));
System.out.println("Long is: " + firstObject.getDouble("gpsLong"));
}
This would print:
Lat is: 8.23324
Long is: 15.0293
The outermost characters in that string are square brackets, so you're not dealing with a JSON object, you have a JSON array.
You said you've used JSONObject in other situations. JSONObject is for objects (which start with a {). Since what you have here is an array, you want to use JSONArray instead.
After creating a JSONArray from this string, calling getJSONObject(0) on it would get you a JSONObject for the array's first element (which is what actually contains the data in the example you've posted). Assuming the structure you posted, you'd need to do something like this:
JSONArray outerArray = new JSONArray(Result);
JSONObject nodeObject = outerArray.getJSONObject(0);
After that you can work with nodeObject like any other JSONObject.

Categories