how to convert JSONObject to JSONArray - android

JSONObject user_values = new JSONObject(json.getString("quotes_cat"));
JSONArray user_subject = new JSONArray(
json.getString("quotes_cat"));
List<String> list = new ArrayList<String>();
for (int i = 0; i < user_subject.length(); i++)
{
list.add(user_subject.getString(i));
}
String[] stringArray = list.toArray(new String[list.size()]);
The problem is
type org.json.JSONArray cannot be converted to JSONObject
JSON output is this
{"status":"ok","response":"Fetched Successfully!","quotes_cat":["Life","Love","Success","Happiness","Funny","Love","Success","Happiness","Funny"]}

Replace this
JSONObject user_values = new JSONObject(
json.getString("quotes_cat"));
with this:
JSONObject user_values = new JSONObject(json);
You need to parse the original JSON String into an JSONObject Java object this way. After that, replace this:
JSONArray user_subject = new JSONArray(
json.getString("quotes_cat"));
with this:
JSONArray user_subject = user_values.getJSONArray("quotes_cat"));
to get the array out of the newly created root JSONObject :-)

Your quotes_cat is jsonArray, so try this:
JSONArray user_subject = new JSONObject(json).getJSONArray("quotes_cat");
List<String> list = new ArrayList<String>();
for (int i = 0; i < user_subject.length(); i++)
{
list.add(user_subject.getString(i));
}
String[] stringArray = list.toArray(new String[list.size()]);
When json is your json string:
String json = "{\"status\":\"ok\",\"response\":\"Fetched Successfully!\",\"quotes_cat\":[\"Life\",\"Love\",\"Success\",\"Happiness\",\"Funny\",\"Love\",\"Success\",\"Happiness\",\"Funny\"]}";

Assuming that json class is JSONObject, I suggest you to use getJSONArray("quotescat") to retrieve your array.

Related

Android Studio: of type org.json.JSONObject cannot be converted to JSONArray

I get error: of type org.json.JSONObject cannot be converted to JSONArray when I try to retrieve JSON values.
JSONArray jsonarray = new JSONArray(data);
for(int i = 0; i < jsonarray.length(); i++){
JSONObject JO = (JSONObject) jsonarray.get(i);
String id = JO.getString("languages");
dataParsed = dataParsed + id;
}
The JSON looks like this (have removed sensitive data)
{
"ip":"",
"type":"",
"continent_code":"EU",
"continent_name":"Europe",
"country_code":"GB",
"country_name":"United Kingdom",
"region_code":"ENG",
"region_name":"England",
"city":"",
"zip":"",
"latitude":,
"longitude":,
"location":{
"geoname_id":,
"capital":"London",
"languages":[
{
"code":"en",
"name":"English",
"native":"English"
}
],
"country_flag":"http:\/\/assets.ipstack.com\/flags\/gb.svg",
"country_flag_emoji":"\ud83c\uddec\ud83c\udde7",
"country_flag_emoji_unicode":"U+1F1EC U+1F1E7",
"calling_code":"44",
"is_eu":true
}
}
I should mention that the data I actually want to retrieve is the name of the language.
You could try this:
JSONObject obj = new JSONObject(data);
JSONObject objLocation = obj.getJSONObject("location");
JSONArray arrayLanguage = objLocation.getJSONArray("languages");
for (int i = 0; i < arrayLanguage.length(); i++) {
JSONObject JO = (JSONObject) arrayLanguage.get(i);
String id = JO.getString("languages");
dataParsed = dataParsed + id;
}

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();
}

android org.json.JSONArray cannot be converted to JSONObject?

[{"Episode Detail":[{"Episode-image":"http:\/\/app.lionforge.com\/comics\/adminpanel\/episode_image\/014929Quincredible_1-6.png","Episode-description":" dsdsdsdsds ","Episode-video":"http:\/\/www.youtube.com\/embed\/KhXTLAdadlw"},{"Episode-image":"http:\/\/app.lionforge.com\/comics\/adminpanel\/episode_image\/015041Quincredible_1-5.png","Episode-description":" avbcabc ","Episode-video":"http:\/\/www.youtube.com\/embed\/5ORBHSJhXew"}]}]
JSONObject jObject=null;
try {
jObject = new JSONObject(response);
JSONArray list = jObject.getJSONArray("Episode Detail");
for (int i = 0; i < list.length(); i++) {
JSONObject element = list.getJSONObject(i);
episodebean bean=new episodebean();
i am getting json exception that JSONArray cannot be converted to JSONObject,how i resolve this ,i am so confuse..,please help me..
use following code
JSONObject jObject=null;
try {
JSONArray array = new JsonArray(response)
jObject = jsonArray.getJSONObject(0);
JSONArray list = jObject.getJSONArray("Episode Detail");
for (int i = 0; i < list.length(); i++) {
JSONObject element = list.getJSONObject(i);
episodebean bean=new episodebean();
your have one jsonArray that has one JsonObject
Change this
jObject = new JSONObject(response);
To
JSONArray jarray = new JSONArray(response);
JSON
[ //json array node
{ // json object node
"Episode Detail": [ // json array episode detail
{ // json obect node j
"Episode-image": "http://app.lionforge.com/comics/adminpanel/episode_image/014929Quincredible_1-6.png",
"Episode-description": " dsdsdsdsds ",
"Episode-video": "http://www.youtube.com/embed/KhXTLAdadlw"
},
{
"Episode-image": "http://app.lionforge.com/comics/adminpanel/episode_image/015041Quincredible_1-5.png",
"Episode-description": " avbcabc ",
"Episode-video": "http://www.youtube.com/embed/5ORBHSJhXew"
}
]
}
]
JSONArray arr = new JSONArray("");
for (int i = 0; i < arr.length(); i++) {
JSONObject c = json_data.getJSONObject(i);
JSONArray arrdata = c.getJSONArray("Episode Detail");
}
The root of your JSON is an JSONArray
response is Array not object.
jObject = new JSONObject(response);
it should be Array instead of object

Extracting values from json file android

My json string is as follows:
i pass it to a json object as follows but i get only the golfs value.
jsonObject = new JSONObject(details_circuit);
System.out.println("jsonObject "+jsonObject.toString());
jsArray = jsonObject.getJSONArray("golfs");
if i do
jsonObject1 = new JSONObject(jsonObject.getString("circuit"));
i cannot get any value. Any idea.
jsonObject1 = new JSONObject(jsonObject.getString("circuit"));//Wrong because circuit is a jsonObject
Use this instead
JSONObject jsonObject1 = jsonObject.getJSONObject("circuit");
or use
JSONObject circuit = (JSONObject)jsonObject.get('circuit');
Reference
JSONObject jsonObject = new JSONObject(details_circuit);
JSONObject circuit=jsonObject.getJSONObject("circuit");
int id=circuit.getInt("#id");
int version=circuit.getInt("#version");
String name=circuit.getString("#name");
String description=circuit.getString("#description");
JSONObject row;
int id ;
int version;
String name;
JSONArray golfs=jsonObject.getJSONObject("golfs");
for(int i=0;i<golfs.length();i++){
row = golfs.getJSONObject(i);
id = row.getInt("id");
version=row.getInt("#version");
name=row.getString("#name");
}
"circuit": { is a JSONObject
Change to
jsonObject1 = (JSONObject)jsonObject.getJSONObject("circuit");
int id = jsonObject1.getInt("#id"):
jsonObject1 = jsonObject.getJSONObject("circuit");
Use following code.
JSONObject json = jParser.getJSONFromUrl(url);
JSONObject json1 = json.getJSONObject("circuit");
int id = json1.getInt("id");
For JsonArray Use following.
JSONArray jarray = json.getJSONArray("golfs");
JSONObject jarray = json.getJSONObject(0);
int id = json1.getInt("id");

How to add values to a string array in android

I have a problem with my code,
I have a json array
[{"Response":{"data":"sibin1"}},{"Response":{"data":"sibin2"}},
{"Response": {"data":"sibin3"}}]
And iam trying to extract the json data using the below code,Here i added only some parts of the coode
JSONArray finalResult = new JSONArray(tokener);
int finalresultlengt=finalResult.length();
JSONObject json_data = new JSONObject();
for (int i = 0; i < finalResult.length(); i++)
{
json_data = finalResult.getJSONObject(i);
System.out.println("json dataa"+json_data.names().toString());
JSONObject menuObject = json_data.getJSONObject("Response");
result= menuObject.getString("data");
System.out.println(result);
}
The code is worked very well
when the value of
i=0 ,result is sibin1
i=1 ,result is sibin2
i=2 ,result is sibin3
But my problem is , i need to store the result in a string array of length finalresultlength inside the given for loop, also i need to print the values in the string array in a for loop outside the given for loop
if anybody knows please help me...........
You could do this way as well.
Create an ArrayList of size 'finalresultlengt' and the add the values in.
list.add(result); // variable 'result' in your case is the value from JSON
If you have more values to be added, create a POJO class.
class POJO {
private String dataVal;
public void setDataVal(String dataVal) {
this.dataVal = dataVal;
}
public String getDataVal() {
return dataVal;
}
}
Then create an ArrayList of type POJO.
ArrayList<POJO> list = new ArrayList<POJO>(finalresultlengt);
EDIT
JSONArray finalResult = new JSONArray(tokener);
int finalresultlengt=finalResult.length();
JSONObject json_data = new JSONObject();
ArrayList<String> list = new ArrayList<String>(finalresultlengt);
for (int i = 0; i < finalResult.length(); i++) {
json_data = finalResult.getJSONObject(i);
System.out.println("json dataa"+json_data.names().toString());
JSONObject menuObject = json_data.getJSONObject("Response");
result= menuObject.getString("data");
list.add(result);
}
Populate values from ArrayList.
for(String value : list)
System.out.println(value);

Categories

Resources