Android (Java) convert JSONArray to JSONObject - java

I have a JSONObject:
try {
JSONObject myJsonObject = new JSONObject("{ \"options\": [\"Oui\", \"Non\"] }");
JSONArray myJsonArray = myJsonObject.getJSONArray("options");
} catch (Exception e) {
e.printStackTrace();
}
myJsonArray.toString() contain:
["Yes", "No"]
I need to convert it to a JSONObject like this:
{ "0": "Yes", "1": "No" }
and also to:
{ "Yes": "Yes", "No": "No" }
Any idea how I can do this?

Of course the answer is :
JSONObject myJsonObject = new JSONObject("{ \"options\": [\"Oui\", \"Non\"] }");
JSONArray myJsonArray = myJsonObject.getJSONArray("options");
JSONObject myJsonObject2 = new JSONObject();
for(int i = 0; i < myJsonArray.length(); i++){
String a = myJsonArray.getString(i);
myJsonObject2.put(a, a);
}
Sorry, I got confused.

There is a method toJSONObject for creating new JSONObjects from a JSONArray.
Try this:
try {
JSONObject myJsonObject = new JSONObject("{ \"options\": [\"Oui\", \"Non\"] }");
JSONArray myJsonArray = myJsonObject.getJSONArray("options");
// creates a new JSON Object with the given keys
JSONObject result = myJsonArray.toJSONObject(myJsonArray);
} catch (Exception e) {
e.printStackTrace();
}

Related

Using "put" method of JSONObject in for loop (java)

I'm trying to use JSONObject's put method in for loop. But I'm not getting Expected output.
Expected output:
{"Result":[{"PostOfficeName":"Bhajan Pura","Pincode":"110096"},{"PostOfficeName":"Gokulpuri","Pincode":"110094"}, and so on...]}
OutPut I'm getting:
{"Result":[{"PostOfficeName":"Bhajan Pura","Pincode":"110096"}]}
here is my code:
try {
JSONObject obj = new JSONObject(loadJsonfromAssets());
JSONArray arr = obj.getJSONArray("Sheet1");
JSONObject finalObj = new JSONObject();
JSONArray ResultArray = new JSONArray();
JSONObject infoObj = new JSONObject();
for (int i=0; i<arr.length();i++){
JSONObject obj1 = arr.getJSONObject(i);
if (obj1.getString("City").equals("New Delhi")){
Log.d("postal", "Found!");
Toast.makeText(this, "" + obj1.getString("Pincode"), Toast.LENGTH_SHORT).show();
infoObj.put("PostOfficeName", obj1.getString("PostOfficeName"));
infoObj.put("Pincode",obj1.getString("Pincode"));
ResultArray.put(infoObj);
}
}
finalObj.put("Result", ResultArray);
System.out.println(finalObj);
} catch (JSONException e) {
e.printStackTrace();
}
Have you tried moving the construction of infoObj inside the loop. By having it outside, you're maintaining state across loop iterations. I suspect you're just updating the same json object each time and adding it to the JSON array. Not sure why you NOT getting duplicates because I do when I run your code.
Change it to this makes it "better"
try {
JSONObject obj = new JSONObject(loadJsonfromAssets());
JSONArray arr = obj.getJSONArray("Sheet1");
JSONObject finalObj = new JSONObject();
JSONArray ResultArray = new JSONArray();
for (int i=0; i<arr.length();i++){
JSONObject obj1 = arr.getJSONObject(i);
if (obj1.getString("City").equals("New Delhi")) {
Log.d("postal", "Found!");
Toast.makeText(this, "" + obj1.getString("Pincode"),
Toast.LENGTH_SHORT).show();
// move instantiation INSIDE loop
JSONObject infoObj = new JSONObject();
infoObj.put("PostOfficeName", obj1.getString("PostOfficeName"));
infoObj.put("Pincode",obj1.getString("Pincode"));
ResultArray.put(infoObj);
}
}
finalObj.put("Result", ResultArray);
System.out.println(finalObj);
} catch (JSONException e) {
e.printStackTrace();
}

Having trouble finding the right JSON path for android project

JSONObject baseJsonResponse = new JSONObject(newsJSON);
JSONObject responseObj = baseJsonResponse.getJSONObject("response");
JSONArray resultArray = responseObj.getJSONArray("results");
for (int i =0;i<resultArray.length();i++){
String sectionName = resultArray.getString("sectionName");}
I want to get the section name for this url:
https://content.guardianapis.com/search?api-key=e11b8d10-d6ef-4fb7-9c12-094c58d37687
You can get Json Value Like this.
JSONObject baseJsonResponse = new JSONObject(newsJSON);
JSONObject responseObj = null;
try {
responseObj = baseJsonResponse.getJSONObject("response");
JSONArray resultArray = responseObj.getJSONArray("results");
int size = resultArray.length();
for (int i =0;i<size;i++){
JSONObject myJson = resultArray.getJSONObject(i);
String sectionName = myJson.getString("sectionName");
}
} catch (JSONException e) {
e.printStackTrace();
}

Append or remove data from JSON

The result i want to get:
[
{"id":1,"name":"example1","description":"An example"},
{"id":2, "name":"example2","description":"Just another example"},
... ]
To add new data to JSON i tried this:
String jsonDataString = ALL MY JSON DATA HERE;
JSONObject mainObject = new JSONObject(jsonDataString);
JSONObject valuesObject = new JSONObject();
JSONArray list = new JSONArray();
valuesObject.put("id", "3");
valuesObject.put("name", "example3");
valuesObject.put("description", "Yet another example");
list.put(valuesObject);
mainObject.accumulate("", list);
But i don't get a proper result.
And how to remove a JSON data depend on the value of the ID ?
Thank's.
To build a fresh JSONArray you can use below codes:
try {
JSONArray jsonArray = new JSONArray();
// Object 1
JSONObject jsonObject1 = new JSONObject();
jsonObject1.put("id", 1);
jsonObject1.put("name", "example1");
jsonObject1.put("description", "An example");
// Object 2
JSONObject jsonObject2 = new JSONObject();
jsonObject2.put("id", 2);
jsonObject2.put("name", "example2");
jsonObject2.put("description", "Just another example");
// Add Object 1 & 2 JSONArray
jsonArray.put(jsonObject1);
jsonArray.put(jsonObject2);
Log.d("JSON", "JSON: " + jsonArray.toString());
} catch (final JSONException e) {
Log.e("FAILED", "Json parsing error: " + e.getMessage());
}
OUTPUT:
D/JSON: JSON: [{"id":1,"name":"example1","description":"An example"},{"id":2,"name":"example2","description":"Just another example"}]
To add new JSONObject into existing JSONArray you can use below codes:
// Your Existing JSONArray
// [{"id":1,"name":"example1","description":"An example"},
// {"id":2, "name":"example2","description":"Just another example"}]
String jsonDataString = "[{\"id\":1,\"name\":\"example1\",\"description\":\"An example\"},{\"id\":2,\"name\":\"example2\",\"description\":\"Just another example\"}]";
try {
JSONArray jsonArray = new JSONArray(jsonDataString);
// Object 3
JSONObject jsonObject3 = new JSONObject();
jsonObject3.put("id", 3);
jsonObject3.put("name", "example3");
jsonObject3.put("description", "Third example");
// Add Object 3 JSONArray
jsonArray.put(jsonObject3);
Log.d("JSON", "JSON: " + jsonArray.toString());
} catch (final JSONException e) {
Log.e("FAILED", "Json parsing error: " + e.getMessage());
}
OUTPUT:
D/JSON: JSON: [{"id":1,"name":"example1","description":"An example"},{"id":2,"name":"example2","description":"Just another example"},{"id":3,"name":"example3","description":"Third example"}]
To remove JSONObject from JSONArray you can use below codes:
// Your Existing JSONArray
// [{"id":1,"name":"example1","description":"An example"},
// {"id":2,"name":"example2","description":"Just another example"},
// {"id":3,"name":"example3","description":"Third example"}]
String jsonDataString = "[{\"id\":1,\"name\":\"example1\",\"description\":\"An example\"},{\"id\":2,\"name\":\"example2\",\"description\":\"Just another example\"},{\"id\":3,\"name\":\"example3\",\"description\":\"Third example\"}]";
try {
JSONArray jsonArray = new JSONArray(jsonDataString);
Log.d("JSON", "JSON before Remove: " + jsonArray.toString());
// Remove Object id = 2
int removeId = 2;
for (int i = 0; i < jsonArray.length(); i++)
{
JSONObject object = jsonArray.getJSONObject(i);
if (object.has("id") && !object.isNull("id")) {
int id = object.getInt("id");
if (id == removeId)
{
jsonArray.remove(i);
break;
}
}
}
Log.d("JSON", "JSON After Remove: " + jsonArray.toString());
} catch (final JSONException e) {
Log.e("FAILED", "Json parsing error: " + e.getMessage());
}
OUTPUT:
D/JSON: JSON Before Remove: [{"id":1,"name":"example1","description":"An example"},{"id":2,"name":"example2","description":"Just another example"},{"id":3,"name":"example3","description":"Third example"}]
D/JSON: JSON After Remove: [{"id":1,"name":"example1","description":"An example"},{"id":3,"name":"example3","description":"Third example"}]
Hope this will help you.
The root object of the json is an array so you should use a JSONArray, not a JSONObject.
String jsonDataString = ALL MY JSON DATA HERE;
JSONArray mainObject = new JSONArray(jsonDataString);
JSONObject valuesObject = new JSONObject();
valuesObject.put("id", "3");
valuesObject.put("name", "example3");
valuesObject.put("description", "Yet another example");
mainObject.put(valuesObject);

org.json.JSONException: Value of Feedback type java.lang.String cannot be converted to JSONArray while converting jsonstring to object

I am new in android development..I just want to remove object from jsonstring.
I have jsonstring and I am converting string into json object and then array..remove object from jsonobject and again convert into jsonstring ,save that string into db..
but I got error that org.json.JSONException: Value Feedback of type java.lang.String cannot be converted to JSONArray
Here is my code:
public JSONArray convertjsonstringtoarray()
{
JSONArray jsonArray=new JSONArray();
String select_json= customizeAdapter.selectCustomizeEntry_jsonmodified();
Log.e("Json String Select",select_json);
try {
JSONObject jsnobject = new JSONObject(select_json);
jsonArray = new JSONArray("Feedback");
jsonArray = jsnobject.getJSONArray("Feedback");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject explrObject = jsonArray.getJSONObject(i);
}
}catch (Exception j){
Log.e("Exception JSON", j.toString());
}
RemoveJSONArray(jsonArray);
Log.e("JSOn ARRAY",jsonArray.toString());
return jsonArray;
}
public static JSONArray RemoveJSONArray( JSONArray jarray) {
JSONArray Njarray=new JSONArray();
try{
for(int i=0;i<jarray.length();i++){
if(i!=1)
Njarray.put(jarray.get(i));
}
}catch (Exception e){e.printStackTrace();}
return Njarray;
}
Here my select_json is :
{"id":0,"name":null,"email":null,"fields":{"Feedback":[{"min":"1","max":"1000","visible":"1","params":"","access":"","registration":"1","type":"text","option1":"","id":1,"option2":"","option3":"","option4":"","fieldcode":"FIELDght66yh","name":"ght66yh","value":"","ordering":1,"tips":"ght66yh","required":"0","published":"1","searchable":"1","options":""},{"min":"1","max":"1000","visible":"1","params":"","access":"","registration":"1","type":"text","option1":"","id":2,"option2":"","option3":"","option4":"","fieldcode":"FIELDbgfhtuu","name":"bgfhtuu","value":"","ordering":2,"tips":"bgfhtuu","required":"0","published":"1","searchable":"1","options":""}]}}
Try below code to parse json response .
try {
JSONObject jsonObject = new JSONObject(response);// here response is your json string
String id = jsonObject.getString("id");
/**
* Same way you can get other string value
*/
JSONObject obj = jsonObject.getJSONObject("fields");
JSONArray array2 = obj.getJSONArray("Feedback");
for (int i = 0; i < array2.length(); i++) {
JSONObject jsonObject2 = array2.getJSONObject(i);
///do something here
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
just create the object of jsonarray .then assign jsnobject.getJSONArray("Feedback") to that..no need to pass "Feedback" string inside the constructor
public JSONArray convertjsonstringtoarray()
{
JSONArray jsonArray=new JSONArray();
String select_json= customizeAdapter.selectCustomizeEntry_jsonmodified();
Log.e("Json String Select",select_json);
try {
JSONObject jsnobject = new JSONObject(select_json);
//assume this object "jsnobject" is contain the below json
//dont know what's this select_json is
/*"{
"Feedback": [
{
"min": "1",
"max": "1000",
"visible": "1",
"params": "",
"access": "",
"registration": "1",
"type": "text",
"option1": "",
"id": 1,
"option2": "",
"option3": "",
"option4": "",
"fieldcode": "FIELDght66yh",
"name": "ght66yh",
"value": "",
"ordering": 1,
"tips": "ght66yh",
"required": "0",
"published": "1",
"searchable": "1",
"options": ""
}]}*/
//jsonArray = new JSONArray("Feedback");//your code is problematic here
//just create the object lik
jsonArray = new JSONArray();
//jsonArray = new JSONObject() //dont know..why you doing that
jsonArray = jsnobject.getJSONArray("Feedback");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject explrObject = jsonArray.getJSONObject(i);
}
}catch (Exception j){
Log.e("Exception JSON", j.toString());
}
RemoveJSONArray(jsonArray);
Log.e("JSOn ARRAY",jsonArray.toString());
return jsonArray;
}
public static JSONArray RemoveJSONArray( JSONArray jarray) {
JSONArray Njarray=new JSONArray();
try{
for(int i=0;i<jarray.length();i++){
if(i!=1)
Njarray.put(jarray.get(i));
}
}catch (Exception e){e.printStackTrace();}
return Njarray;
}

JSONArray does not work when I am getting the JSON string from the server

I've looked up some answers but am not sure why mine is failing exactly...
The code looks something like this
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
String json = EntityUtils.toString(httpEntity);
//Convert to JsonArray
JSONArray jsonArray = new JSONArray(json);
Log.i(DEBUG_TAG, Integer.toString(jsonArray.length()));
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
Log.i(DEBUG_TAG, jsonObject.getString(KEY_ID));
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(KEY_ID, jsonObject.getString(KEY_ID));
map.put(KEY_TITLE, jsonObject.getString(KEY_TITLE));
map.put(KEY_ARTIST, jsonObject.getString(KEY_ARTIST));
map.put(KEY_DURATION, jsonObject.getString(KEY_DURATION));
map.put(KEY_VOTECOUNT, jsonObject.getString(KEY_VOTECOUNT));
map.put(KEY_THUMB_URL, jsonObject.getString(KEY_THUMB_URL));
map.put(KEY_GENRE, jsonObject.getString(KEY_GENRE));
//Adding map to ArrayList
if (Integer.parseInt(jsonObject.getString(KEY_VOTECOUNT)) == -1){
//If VoteCount is -1 then add to header
headerList.add(map);
}else {
songsList.add(map);
}
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
When I run logcat on String json, it seems to show correct info which is kind of like this...
{
"userdata": [
{
"id": "8",
"title": "Baby One More Time",
"artist": "Britney Spears",
"duration": "03:24:00",
"votes": "0",
"thumb_url": "http://api.androidhive.info/music/images/dido.png",
"genre": null
},
{
"id": "2",
"title": "As Long As You Love Me",
"artist": "Justin Bieber",
"duration": "05:26:00",
"votes": "0",
"thumb_url": "http://api.androidhive.info/music/images/enrique.png",
"genre": "Rock"
}
]
}
and the logcat on
JSONArray jsonArray = new JSONArray(json);
tells me that jsonArray.length()
10-31 22:57:28.433: W/CustomizedListView(26945): error! Invalid index
0, size is 0
Please let me know
Thank you,
The problem is it's not a JSON Array. It's a JSON object, JSON array starts with a [ and ends with a ]
and JSON object starts with a { and end with a }
for further reference you can see it here -> http://www.json.org/
to fix it you should convert your json string to json object first then parse the json object to get the json array
this is an example of parsing json array from jsonobject
void ParseAPIWithJSON()
{
String readGooglePlace = readGooglePlaceAPI();
try
{
InputStream is = new ByteArrayInputStream(readTwitterFeed.getBytes("UTF-8"));
byte [] buffer = new byte[is.available()];
while (is.read(buffer) != -1);
String jsontext = new String(buffer);
JSONObject entries = new JSONObject(jsontext);
JSONArray hasil = entries.getJSONArray("results");
results = hasil.getString(o);
Log.i("TAG", results);
int i;
Log.i("TAG", Integer.toString(hasil.length()));
numberofPlaces = hasil.length();
for (i=0;i<hasil.length();i++)
{
JSONObject data = hasil.getJSONObject(i);
namePlaces[i] = data.getString("name");
Log.i("TAG", namePlaces[i]);
JSONObject geometry = data.getJSONObject("geometry");
JSONObject location = geometry.getJSONObject("location");
latPlaces[i] = location.getDouble("lat");
longPlaces[i] = location.getDouble("lng");
Log.i("TAG", "Lat : "+latPlaces[i]+" Long : "+longPlaces[i]);
}
}
catch (Exception je)
{
Log.e("TEST1", je.getMessage());
}
}
from that whole code I think you only need to understand this
String jsontext = new String(buffer);
JSONObject entries = new JSONObject(jsontext);
JSONArray hasil = entries.getJSONArray("results");
convert string->jsonobject->jsonarray->get value
You need to replace :
JSONArray jsonArray = new JSONArray(json);
with
JSONArray jsonArray = new JSONObject(json).getJSONArray("userdata");
Into your case JSON is starting from jsonobject not the jsonArray, so first you have the declare jsonobject not jsonarray.
try {
JSONObject jsonObject = new JSONObject();
JSONArray jsonArray = jsonObject.getJSONArray("userdata");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonUserdata = jsonArray.getJSONObject(i);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(KEY_ID, jsonUserdata.getString(KEY_ID));
map.put(KEY_TITLE, jsonUserdata.getString(KEY_TITLE));
map.put(KEY_ARTIST, jsonUserdata.getString(KEY_ARTIST));
map.put(KEY_DURATION, jsonUserdata.getString(KEY_DURATION));
map.put(KEY_VOTECOUNT, jsonUserdata.getString(KEY_VOTECOUNT));
map.put(KEY_THUMB_URL, jsonUserdata.getString(KEY_THUMB_URL));
map.put(KEY_GENRE, jsonUserdata.getString(KEY_GENRE));
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
For the more information go with link:
http://www.androidhive.info/2012/01/android-json-parsing-tutorial/
try this.
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
String response_string;
try {
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
HttpEntity httpEntity = response.getEntity();
InputStream is = httpEntity.getContent();
InputStreamReader isr = new InputStreamReader(is);
char[] arr = new char[8*1024]; // 8K at a time
StringBuffer buf = new StringBuffer();;
int numChars;
while ((numChars = isr.read(arr,0,arr.length))>0)
{
buf.append(arr,0,numChars);
}
response_string = buf.toString();
}
catch (ClientProtocolException e)
{
response_string = "Network Error : " + e.getMessage();
e.printStackTrace();
}
catch (IOException e)
{
response_string = "Network Error : " + e.getMessage();
e.printStackTrace();
}
catch(Exception e)
{
response_string = "Network Error : " + e.getMessage();
e.printStackTrace();
}
JSONArray jsonArray = new JSONArray(response_string);

Categories

Resources