Here you get JSONObject so change this line:
JSONArray jsonArray = new JSONArray(readlocationFeed);
with following:
JSONObject jsnobject = new JSONObject(readlocationFeed);
and after
JSONArray jsonArray = jsnobject.getJSONArray("locations");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject explrObject = jsonArray.getJSONObject(i);
}
Answer from kyogs on Stack OverflowHere you get JSONObject so change this line:
JSONArray jsonArray = new JSONArray(readlocationFeed);
with following:
JSONObject jsnobject = new JSONObject(readlocationFeed);
and after
JSONArray jsonArray = jsnobject.getJSONArray("locations");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject explrObject = jsonArray.getJSONObject(i);
}
Input String
[
{
"userName": "sandeep",
"age": 30
},
{
"userName": "vivan",
"age": 5
}
]
Simple Way to Convert String to JSON
public class Test
{
public static void main(String[] args) throws JSONException
{
String data = "[{\"userName\": \"sandeep\",\"age\":30},{\"userName\": \"vivan\",\"age\":5}] ";
JSONArray jsonArr = new JSONArray(data);
for (int i = 0; i < jsonArr.length(); i++)
{
JSONObject jsonObj = jsonArr.getJSONObject(i);
System.out.println(jsonObj);
}
}
}
Output
{"userName":"sandeep","age":30}
{"userName":"vivan","age":5}
Just convert use JSONArray,
import java.util.Arrays;
import org.json.JSONArray;
String[] inputs = new String[] {"foo", "bar"};
JSONArray jsonArray = new JSONArray(Arrays.asList(inputs));
A popular solution for Android would be the use of GSON: https://code.google.com/p/google-gson/
The package provides simple toJson and fromJson methods on its main converter object, so you get there quite easily. Alternatives like Jackson often require some additional preparation of the converted objects.
Videos
This should help you.
Edit:
Maybe this is what you need:
ArrayList<String> stringArray = new ArrayList<String>();
JSONArray jsonArray = new JSONArray();
for(int i = 0, count = jsonArray.length(); i< count; i++)
{
try {
JSONObject jsonObject = jsonArray.getJSONObject(i);
stringArray.add(jsonObject.toString());
}
catch (JSONException e) {
e.printStackTrace();
}
}
Assume that you already have JSONArray jsonArray:
String[] stringArray = new stringArray[jsonArray.length()];
for(int i = 0, count = jsonArray.length(); i< count; i++)
{
try {
String jsonString = jsonArray.getString(i);
stringArray[i] = jsonString.toString();
}
catch (JSONException e) {
e.printStackTrace();
}
}
Remove the slashes:
String json = {"phonetype":"N95","cat":"WP"};
try {
JSONObject obj = new JSONObject(json);
Log.d("My App", obj.toString());
} catch (Throwable t) {
Log.e("My App", "Could not parse malformed JSON: \"" + json + "\"");
}
This method works
String json = "{\"phonetype\":\"N95\",\"cat\":\"WP\"}";
try {
JSONObject obj = new JSONObject(json);
Log.d("My App", obj.toString());
Log.d("phonetype value ", obj.getString("phonetype"));
} catch (Throwable tx) {
Log.e("My App", "Could not parse malformed JSON: \"" + json + "\"");
}
Something like this:
ArrayList<String> jsonStringToArray(String jsonString) throws JSONException {
ArrayList<String> stringArray = new ArrayList<String>();
JSONArray jsonArray = new JSONArray(jsonString);
for (int i = 0; i < jsonArray.length(); i++) {
stringArray.add(jsonArray.getString(i));
}
return stringArray;
}
You could try something like:
new JSONArray(jsonString)
or if it is a property:
jsonObject.getJSONArray(propertyName)
This is how to initialize a JSON parser:
JSONObject jsonObject = new JSONObject(jsonString);
That will give you the entire string as a Json Object. From there, pull out an individual array as a JsonArray, like this:
JSONArray jsonArray = jsonObject.getJSONArray("LotPrizes");
To access each "LotPrizes" you can use for loop logic:
for(int i=0;i<jsonArray.length();i++)
{
JSONObject curr = jsonArray.getJSONObject(i);
prize = curr.getString("Prize")
//Do stuff with the Prize String here
//Add it to a list, print it out, etc.
}
EDIT: Final code after your JSON edit:
JSONArray jsonArray = null;
String jsonString = <your string>
String currPrize = null;
JSONObject jsonObject = new JSONObject(jsonString);
jsonArray = jsonObject.getJSONArray("data");
for(int i=0;i<jsonArray.length();i++)
{
JSONArray currLot = jsonArray.getJSONObject(i);
for(int j=0; j<currLot.length();j++)
{
JSONobject curr = currLot.getJSONObject(j);
currPrize = curr.getString("Prize");
//Do something with Prize
}
}
This code is functional and I'm using an almost identical version in my code. Hope this (finally) works for you.
You can retrieve the jsondata from your string as follows ..
JSONObject json = new JSONObject(jsonString);
JSONArray jData = json.getJSONArray("data");
for (int i = 0; i < jData.length(); i++) {
JSONObject jo = jData.getJSONObject(i);
JSONArray jLotPrizes = jo.getJSONArray("LotPrizes");
for (int j = 0; j < jLotPrizes.length(); j++) {
JSONObject jobj = jLotPrizes.getJSONObject(j);
Log.i("Prize", "" + jobj.getString("Prize"));
Log.i("Range", "" + jobj.getString("Range"));
}
}
If you're talking about using the JSON in java library, then since your input string is a JSON object, not a JSON array, you should first load it using JSONObject:
String response=getResponseFromServer();
JSONObject jsonObject = new JSONObject(response);
After that, you can use toJSONArray() to convert a JSONObject to JSONArray given an array of key strings:
String[] names = JSONObject.getNames(jsonObject);
JSONArray jsonArray = jsonObject.toJSONArray(new JSONArray(names));
If you do a search right here on StackOverflow for Java String to JSONArray, you should get this answer: Converting from JSONArray to String then back again
JSONArray jArray;
String s = jArray.toString(); // basically what you have ;)
JSONArray newJArray = new JSONArray(s);
For sure, data is a String (character surrounded by quotes), it can't be read as a JSONArray.
If you can't make your php to generate a JSON array, what you can do on Android size, is to get the data string with :
String data = httpResult.getString("data");
then you can create a JSONARRAY with :
JSONArray constructor
JSONArray dataArray = new JSONArray(data)
"data":"[
{\"id\":\"5099\",\"user_id\":\"892\"},
{\"id\":\"5100\",\"user_id\":\"892\"}
....
]"
is a string
But
"data":[
{"id":"5099","user_id":"892"},
{"id":"5100","user_id":"892"}
....
]
is array
The problem is not the JSONArray.toString(), as @Selvin mentioned.
From JSONArray source:
/**
* Encodes this array as a compact JSON string, such as:
* <pre>[94043,90210]</pre>
*/
@Override public String toString() {
try {
JSONStringer stringer = new JSONStringer();
writeTo(stringer);
return stringer.toString();
} catch (JSONException e) {
return null;
}
}
/**
* Encodes this array as a human readable JSON string for debugging, such
* as:
* <pre>
* [
* 94043,
* 90210
* ]</pre>
*
* @param indentSpaces the number of spaces to indent for each level of
* nesting.
*/
public String toString(int indentSpaces) throws JSONException {
JSONStringer stringer = new JSONStringer(indentSpaces);
writeTo(stringer);
return stringer.toString();
}
The problem is that you need to convert your ChecklistAnswer to JSON object first for your JSONArray to work properly.
Again from Javadoc:
/**
* A dense indexed sequence of values. Values may be any mix of
* {@link JSONObject JSONObjects}, other {@link JSONArray JSONArrays}, Strings,
* Booleans, Integers, Longs, Doubles, {@code null} or {@link JSONObject#NULL}.
* Values may not be {@link Double#isNaN() NaNs}, {@link Double#isInfinite()
* infinities}, or of any type not listed here.
...
In my ChecklistAnwer class i added:
public JSONObject toJsonObject(){
JSONObject json = new JSONObject();
try {
json.put("questionId", questionId);
json.put("checklistId", checklistId);
json.put("answer", answer);
json.put("remark", remark);
} catch (JSONException e) {
e.printStackTrace();
}
return json;
}
and in my other class:
JSONArray answers = new JSONArray();
ChecklistAnswer answer = new ChecklistAnswer(questions.get(id).id, 2, cb.isChecked(), text.getText().toString());
answers.put(answer.toJsonObject());
if i filled the array:
String js = answers.toString(1);
and that returns:
[
{
"answer": true,
"questionId": 1,
"remark": "",
"checklistId": 2
},
{
"answer": false,
"questionId": 4,
"remark": "teesxfgtfghyfj",
"checklistId": 2
},
{
"answer": true,
"questionId": 4,
"remark": "",
"checklistId": 2
},
{
"answer": true,
"questionId": 4,
"remark": "",
"checklistId": 2
},
{
"answer": true,
"questionId": 4,
"remark": "",
"checklistId": 2
},
{
"answer": true,
"questionId": 4,
"remark": "",
"checklistId": 2
},
{
"answer": true,
"questionId": 4,
"remark": "",
"checklistId": 2
}
]
thanks to @Selvin