I have a JSON Array like this:
[4, 3, 2, 1,...]
It is a simple array, and I am not able to find a single tutorial that tells me how to parse this array. I want to assign each element to a string Array that I have created like:
String H[];
I always get stuck when it comes to returning a value from a method, I get confused. For Example:
Within the Oncreate() method, after initializing all variables I type:
solarData();
//displaying only one value from the String Array H[];
TextView.setText(H[0]);
public JSONArray solarData() throws JSONException{
//After getting response from HttpClient and getting result
JSONArray jArray = new JSONArray(result);
for(int i=0;i<jArray,length();i++){
String H[i] = jArray.getJSONObject(i).toString();
}
return jArray;
}
Now what is it returning? I want it to return the String Array. So that I can display any value I want from the String Array to which I am storing these values.
From the JSONArray documentation, you can see there is a constructor that takes a valid JSON string and does all of the parsing work for you. You seem to have identified this already.
The problem here is that in each iteration of your for loop, you are attempting to create a new String array. You should initialize your array before the loop, and then populate its contents after initializing it. Something like this should work for you:
public JSONArray solarData() throws JSONException{
JSONArray jArray = new JSONArray(result);
// consider renaming H to something meaningful (e.g. planetList)
String H[] = new String[jArray.length()];
for (int i=0; i < jArray,length() ;i++) {
H[i] = jArray.getJSONObject(i).toString();
}
return jArray;
}
Related
I'm fairly new to Android Studio and Java, and I'm working on an app that takes data from Unsplash's API and displays it. However, I'm getting a JSON typeMismatch error, and I'm not sure how to correctly extract the data. Technically I'm getting back an array of JSONObjects, but I'm finding that simply changing JSONObject to JSONArray is not the correct approach.
I believe the problem is with the following lines of code: What I want to do is get the user (photographer) name and profile image, and the image they're posting.
Any help is greatly appreciated!
private NewPhotos getNewPhotos(String jsonData) throws JSONException {
JSONObject unsplash = new JSONObject(jsonData);
JSONObject user = unsplash.getJSONObject("user");
return new NewPhotos();
}
This is the JSON I'm getting back
This is the error message
You need first, cast JSON ARRAY.
You didn't put all json file, but it seems to be an array first.
private NewPhotos getNewPhotos(String jsonData) throws JSONException {
JSONArray unsplash = new JSONArray(jsonData);
for (int i = 0; i < unsplash.length(); i++) {
JSONObject jsonObj = (JSONObject) unsplash.get(i);
JSONObject user = jsonObj.getJSONObject("user");
// Do something with user
}
// Your implementation
return new NewPhotos();
}
This doesn't work for you? :
JSONObject unsplash = new JSONObject(jsonData);
JSONArray user = unsplash.getJSONArray("user");
Cause in your code you're trying to assign jsonArray to jsonObject.
You can't convery JSON Array into a Json object. Rafaela is right. You need to pass the string in Json array and then loop through each object to access user json.
I am trying to parse json but it gives me exception.
I hardcoded expected json as String like this
String stringJSON="[{\"value1\":\"ABC567123\",\"end_at\":\"08/28/2014 09:10:00\",\"start_at\":\"04/25/2016 09:20:00\"}]";
Valid json is like this
[
{
"value1": "ABC567123",
"end_at": "08/28/2014 09:10:00",
"start_at": "04/25/2016 09:20:00"
}
]
Now I am trying to parse json like below and getting exception.
JSONObject responseObJ;
try {
responseObJ= new JSONObject(stringJSON); //error here
if(responseObJ!=null){
//do something
}
} catch (Exception e) {
e.printStackTrace();
return null;
}
Please suggest what to do?
//hard coded it for temporary - json result is expected to exact same
stringJSON is contains JSONArray instead of JSONObject as root element in JSON String.
Either remove [] from start and end of String according to current code or if multiple JSONObject's is available in JSONArray then get JSONArray from stringJSON :
JSONArray responseObJ= new JSONArray(stringJSON);
[ ] they show that it has an array of objects in it so you can retrieve it like this
JSONArray jsonArray= new JSONArray(stringJSON);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jObject.getJSONObject(i);
// here you can get the values of objects stored in the jsonObject
}
In your case you have only one object so you don't have to use loop instead you can get it like this
JSONArray jsonArray= new JSONArray(stringJSON);
JSONObject jsonObject = jObject.getJSONObject(0);
yes as you said its valid json but its JsonArray not JsonObject.
Just remove [] from start and end.
your string should be
String stringJSON="{\"value1\":\"ABC567123\",\"end_at\":\"08/28/2014 09:10:00\",\"start_at\":\"04/25/2016 09:20:00\"}";
or if you want to work with current string then use JsonArray instead of JsonObject
JSONArray responseObJ= new JSONArray(stringJSON);
Can you try Deserialize method of ScriptSerializer class? Like:
var scriptSerializer = new JavaScriptSerializer();
var obj = scriptSerializer.Deserialize<Object>(str);
Well I'm new to Android. I'm getting a JSON string from a remote URL.
[{"key":"myString1","val":"myValue1"},{"key":"myString2","val":"myValue2"},{"key":"myString3","val":"myValue3"},{"key":"myString4","val":"myValue4"},{"key":"myString5","val":"myValue5"}]
I just need to parse this JSON string & display all key-val pair. I tried something like below from one of the tutorial.
JSONArray jArray = new JSONArray(str);
json = jArray.getJSONObject(0); //This will take first pair.
But I don't know the syntax for iterating through whole json object. Any help would be appreciated. Thanks in Advance.
There's nothing special in it. You do it like iterating any other array.
Let's say you have two String arrays to be filled with values: String[] mKey, mValue
Reading from JSON array will be like:
for (int i = 0; i < array.length(); i++) {
JSONObject object = array.getJSONObject(i);
mKey[i] = object.getString("key");
mValue[i] = object.getString("val");
}
How can I parse json from the URL? below is my json structure which does not has tags.
[{"channelId":"0465CDBE","channelName":"ATV2"},{"channelId":"06E6923B1","channelName":"Phoenix"},{"channelId":"07B4FB7ed","channelName":"N24"},{"channelId":"115B73E39","channelName":"ORF2"},
Simply get the JSONArray
JSONArray jArr = new JSONArray(jsonString);
for(int i=0;i<jArr.length;i++)
{
String jChannel = jArr.getJSONObject(i).getString("channelId");
String jChannelName = jArr.getJSONObject(i).getString("channelName");
//you can now play with these variables or add to some list or do whatever you like.
}
The outer object is a JSONArray, so you can iterate it with a "for".
Inside your json array, you have simple json objects. You can parse it by key or iterate the keys.
You can user json object and get the value with getJSONArray
examples:
testob = {"channelId":"07B4FB7ed","channelName":"N24"}, {"channelId":"115B73E39","channelName":"ORF2"},
JSONObject jsonObject = new JSONObject(testob);
JSONArray dataArray = jsonObject.getJSONArray("data");
JSONObject jsonProductData = dataArray.getJSONObject(0);
I got the Json response. I am not able to get the values from the string.my string is
Json_response is
{"NameAllList":[{"Current":{"time":"2012-02-21T08:04:21","Name":"abcd"},
"Next":{"Name":"data1","StartTime":"2012-02-21T08:06:21"}},{"Current":{"time":"2012-02-21T08:14:21","Name":"defg"},
"Next":{"Name":"data2","StartTime":"2012-02-21T08:24:21"}},{"Current":{"time":"2012-02-21T08:28:21","Name":"ghij"},
"Next":{"Name":"data3","StartTime":"2012-02-21T08:34:21"}},{"Current":{"time":"2012-02-21T08:40:21","Name":"knmo"},
"Next":{"Name":"data4","StartTime":"2012-02-21T08:48:21"}}]}
and i tried this.
JSONObject jsonObj = new JSONObject(json_response);
JSONObject subObj = jsonObj.getJSONObject("Current");
String name_current =subObj.getString("Name");
but i am not able to get the value of "Name". what mistake i have done. provide the link to do the above parsing.
first of all, your JSON response is having NameAllList as a JSON Array of objects.
So you have to fetch JSON Array first, then you can fetch one-by-one object.
for example:
JSONObject jsonString = (new JSONObject(json_response_string));
JSONArray array = jsonString.getJSONArray("NameAllList");
for(int i=0; i<array.length(); i++)
{
// Retrieve Current object as such
JSONObject objCurrent = array.getJSONObject("Current");
// Retrieve Next object as such
JSONObject objNext = array.getJSONObject("Next");
}
You are not parsing json properly, so you are not able to fetch value of Name. Please note JSON Annotation [] represent JSONArray, and {} respresent JSONObject, so method to get current item's name is:
JSONObject jsonObj = new JSONObject(json_response_string);
JSONArray jsonArr=jsonObj.getJSONArray("NameAllList");
String Hora_name_current="";
for(int i=0;i<jsonArr.length();i++)
{
JSONObject obj=jsonArr.get(i);
try{
JSONObject subObj = obj.getJSONObject("Current");
Hora_name_current =subObj.getString("Name");
break;
}catch(JSONException ex)
{
}
}
looks like you're trying to use JSONObject when you should be using JSONArray for the second request. Try this:
JSONObject jsonString = (new JSONObject(json_response_string));
JSONArray array = jsonString.getJSONArray("NameAllList");
In your JSON return, "NameAllList is actually an array and needs to be handled as such. Once you set it to "array", you can then run a for loop and treat it like any other array in Java.
Let me know if that helps.
David
JSONObject jsonObj = new JSONObject(json_response_string);
JSONArray jsonArray = jsonObj.getJSONArrays("NameAllList");