I am trying to parse a key from JSONArray which is:
{
"server": [
{
"id": "1",
"name": "Steve",
"email": "test#gmail.com",
"phone": "1001001000"
}
]
}
Since, the key, which is id, name, email, and phone can be dynamically changed, we have to parse the result without teaching the key value. That is, the system has to parse both the key and the value. So I thought getting an array and using the iterator.hasNext() will solve the problem.
JSONObject jsonObject = new JSONObject(stringBuilder.toString().trim());
JSONArray jsonArray = jsonObject.getJSONArray("server");
for (int current = 0; current < jsonArray.length(); current++){
JSONObject json_object = jsonArray.getJSONObject(current);
Iterator iterator = json_object.keys();
while (iterator.hasNext()){
hashMap.put(iterator.next().toString(), json_object.getString(iterator.next().toString()));
}
}
It doesn't work properly whether changing the iterator to jsonObject.keys() or json_object.keys(), but only parses the key value of "id", and can't parse the name, email, phone.
This is how I get the JSON file:
$result = mysqli_query($conn, $sql);
$data = array();
if ($result){
while($row=mysqli_fetch_array($result)){
array_push($data,
array('id'=>$row[1],
'name'=>$row[2],
'email'=>$row[3],
'phone'=>$row[4]
));
}
header('Content-Type: application/json; charset=utf8');
$json = json_encode(array("server"=>$data), JSON_PRETTY_PRINT+JSON_UNESCAPED_UNICODE);
echo $json;
Try this
JSONObject jsonObject = null;
try {
jsonObject = new JSONObject(loadJSONFromAsset());
JSONArray jsonArray = jsonObject.getJSONArray("server");
for (int current = 0; current < jsonArray.length(); current++){
JSONObject json_object = jsonArray.getJSONObject(current);
Iterator iterator = json_object.keys();
while( iterator.hasNext() ) {
String key = (String)iterator.next();
if ( json_object.get(key) instanceof String ) {
hashMap.put(key, json_object.getString(key));
}
}
}
} catch (JSONException e) {
e.printStackTrace();
}
Log.e("OUTPUT", Arrays.asList(hashMap).toString());
OUTPUT
Related
How to parse JSON values in this format? I want to get the details of the data element but inside data there are 'dates' and inside dates there is array containing two more elements. I want to get all the dates first inside data and then within these dates I want all the information within these dates. How can I achieve this? Please Help. I tried with below code but it hasn't worked
try {
JSONObject jsonObject = new JSONObject("data");
JSONArray jsonArray =jsonObject.getJSONArray(String.valueof(cuurentdate));
JSONArray session;
for (int i = 0; i < jsonArray.length() - 1; i++) {
jsonObject = jsonArray.getJSONObject(i);
session= jsonObject.getJSONArray("session");
Log.d("MyLog", session + "");
}
} catch (JSONException e) {
e.printStackTrace();
}
Following is the format
{
"status": 1,
"status_code": 200,
"data": {
"2018-02-11": [
{
"session": "01:00 AM",
"place": true
},
{
"session": "02:00 AM",
"place": true
}
],
"2018-02-12": [
{
"session": "01:00 AM",
"place": true
},
{
"session": "02:00 AM",
"place": true
}
]
}
}
You just need to pass the response string to the method. You can try this:
private void jsonParsing(String jsonString) {
// String jsonString = "{ \"status\": 1, \"status_code\": 200, \"data\": { \"2018-02-11\": [ { \"session\": \"01:00 AM\", \"place\": true }, { \"session\": \"02:00 AM\", \"place\": true } ], \"2018-02-12\": [ { \"session\": \"01:00 AM\", \"place\": true }, { \"session\": \"02:00 AM\", \"place\": true } ] } }";
try {
JSONObject jsonObject = new JSONObject(jsonString);
JSONObject dataObj = jsonObject.getJSONObject("data");
Iterator<String> iter = dataObj.keys();
Log.e(TAG, "jsonParsing: "+iter );
while (iter.hasNext()) {
String key = iter.next();
JSONArray datesArray = dataObj.getJSONArray(key);
ArrayList<String> sessions = new ArrayList<String>();
for (int i = 0; i < datesArray.length(); i++) {
JSONObject datesObject = datesArray.getJSONObject(i);
sessions.add(datesObject.getString("session"));
}
Log.d("MyLog", sessions + "");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
(1) get JSONObject of Main json
JSONObject objMain = new JSONObject("your json string");
(2)get JSONObject of "data" from main json
JSONObject jsonData = objMain.getJSONObject("data")
(3) get all keys (dates) from object "data"
Iterator<String> iter = jsonData.keys();
while (iter.hasNext()) {
String key = iter.next();
try {
JSONArray arrayDate = objData.getJSONArray(key)
for (i = 0; i < arrayDate.length(); i++) {
JSONObject objDate = arrayDate.getJSONObject(i)
Log.d("#session :", "" + objDate.getString("session"))
Log.d("#place :", "" + objDate.getBoolean("place"))
}
} catch (JSONException e) {
// Something went wrong!
}
}
try this one code
IN THIS CODE jsonMstObject IS TEMP OBJECT YOU HAVE TO USE YOUR API RESPONSE JSONobject INSTEAD OF jsonMstObject
try {
JSONObject jsonMstObject = new JSONObject("{"status":1,"status_code":200,"data":{"2018-02-11":[{"session":"01:00 AM","place":true},{"session":"02:00 AM","place":true}],"2018-02-12":[{"session":"01:00 AM","place":true},{"session":"02:00 AM","place":true}]}}");
JSONObject jsonObject = jsonMstObject.getJSONObject("data");
JSONArray jsonArray =jsonObject.getJSONArray(String.valueof(cuurentdate));
ArrayList<String> arrSession = new ArrayList<String>();
for (int i = 0; i < jsonArray.length(); i++) {
jsonObject = jsonArray.getJSONObject(i);
arrSession.add(jsonObject.getString("session"));
}
Log.d("MyLog", arrSession + "");
} catch (JSONException e) {
e.printStackTrace();
}
in this code arrSession is your session string array
Ex. you passed cuurentdate = "2018-02-11" then you recived result like
[01:00 AM, 02:00 AM]
Note: this code is worked based on your cuurentdate param. This is code for get static date array from data and create String Array.
Currently I'm trying to display JSON data (hosted on a Webserver) in a ListView in Android. The App correctly receives the data but is unable to process it further to display it in said ListView.
The error is as follows:
JSON parsing error: Value ... of type org.json.JSONArray cannot be converted to JSONObject
The JSON data I'm trying to parse looks like the following:
[{"idBuch":1,"autor":"Erich Maria Remarque","name":"Im Westen nichts Neues","preis":20,"buchtyp":{"idBuchtyp":3,"typenamen":"Geschichte"}}]
The code that processes the received JSON-String:
try{
JSONObject jsonObject = new JSONObject(jsonStr);
JSONArray books = jsonObject.getJSONArray("book");
for(int i = 0; i < books.length(); i++){
JSONObject obj = books.getJSONObject(i);
String idBook = obj.getString("idBuch");
String author = obj.getString("autor");
String name = obj.getString("name");
String price = obj.getString("preis");
JSONObject booktype = obj.getJSONObject("buchtyp");
String idBooktype = booktype.getString("idBuchtyp");
String typename = booktype.getString("typenamen");
HashMap<String, String> book = new HashMap<>();
book.put("idBook", idBook);
book.put("author", author);
book.put("name", name);
book.put("price", price);
book.put("genre", typename);
bookList.add(book);
} }catch(final JSONException e)
I am aware of the fact that there are a lot of similar questions on this site but I still had no success regarding this issue. Thank you in advance.
The JSON that you provided only contains an array.
[
{
"idBuch": 1,
"autor": "Erich Maria Remarque",
"name": "Im Westen nichts Neues",
"preis": 20,
"buchtyp": {
"idBuchtyp": 3,
"typenamen": "Geschichte"
}
}
]
However, your code expects the root to be an object with field book.
{
"book": [
{
"idBuch": 1,
"autor": "Erich Maria Remarque",
"name": "Im Westen nichts Neues",
"preis": 20,
"buchtyp": {
"idBuchtyp": 3,
"typenamen": "Geschichte"
}
}
]
}
In this case, try replacing the line:
JSONObject jsonObject = new JSONObject(jsonStr);
with
JSONArray books = new JSONArray(jsonStr);
and proceed as normal. Your end result should look like:
try {
JSONArray books = new JSONArray(jsonStr);
for (int i = 0; i < books.length(); i++) {
JSONObject obj = books.getJSONObject(i);
String idBook = obj.getString("idBuch");
String author = obj.getString("autor");
String name = obj.getString("name");
String price = obj.getString("preis");
JSONObject booktype = obj.getJSONObject("buchtyp");
String idBooktype = booktype.getString("idBuchtyp");
String typename = booktype.getString("typenamen");
HashMap < String, String > book = new HashMap < > ();
book.put("idBook", idBook);
book.put("author", author);
book.put("name", name);
book.put("price", price);
book.put("genre", typename);
bookList.add(book);
}
} catch (final JSONException e) {
e.printStackTrace()
}
This question already has answers here:
How do I parse JSON in Android? [duplicate]
(3 answers)
Closed 6 years ago.
I currently have the following JSON structure:
{
"Apps": [
{
"column1": "sample string 1",
"column2": true
},
{
"column1": "sample string 1",
"column2": true
}
],
"param": true
}
How do I get the values of the column1 and column2? What I only know how to parse is a JSONObject within a JSONArray.
JSONObject jSONObject = new JSONObject(yourStrinig);
JSONArray jArray = jSONObject.getJSONArray("Apps");
for (int i = 0; i < jArray.length(); i++) {
JSONObject childrenObject = jArray.getJSONObject(i);
String column1 = childrenObject.getString("column1");
String column2 = childrenObject.getString("column2");
}
Something like this.
// Get a reference to the JSON object
JSONObject jSONObject = new JSONObject(stringJsonResponse);
// Getting the JSON array node
JSONArray jsonAray = jSONObject.getJSONArray("Apps");
// Looping through the json array
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject childrenObject = childrenArray.getJSONObject(i);
...
...
...
}
You can take a look at how I parsed JSON data when I received similar data https://github.com/gSrikar/AskReddit/blob/master/app/src/main/java/com/example/srikar/askreddit/MainActivity.java
with this you can loop through all elements
private void showJSON(String response){
String name="";
String phone_number="";
try {
JSONObject jsonObject =new JSONObject(response);
JSONArray result = jsonObject.getJSONArray(config.JSON_ARRAY);
for(int x=0;x<result.length();x++) {
JSONObject collegeData = result.getJSONObject(x);
name = collegeData.getString(config.KEY_NAME);
phone_number = collegeData.getString(config.KEY_PHONE_NUMBER);
//you can save your data in list here
}
} catch (JSONException e) {
e.printStackTrace();
}
}
Here is my JSON file:
{
"server_response": [{
"bmw": "",
"mercedes": "",
"honda": "civic",
"toyota": "corolla",
"gmc": "",
"chevy": ""
}]
}
Here is my Android code:
try {
JSONObject jsonResponse = new JSONObject(JSON_STRING);
JSONArray jsonMainNode = jsonResponse.optJSONArray("server_response");
for (int i = 0; i < jsonMainNode.length(); i++) {
JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
//this is the problem here. How can I get JSON that has a result like Honda and Toyota?
{variable name} = jsonChildNode.optString("{problem is here}");
CarsModel carsModel new CarsModel( {variable name} {variable name} );
}
} catch (JSONException e) {
e.printStackTrace();
}
The problem is in the Android code as you can see. I want it to only get the JSON that is not empty, for example honda and toyota.
How can replace {variable name} with in this case, honda and then replace {problem is here} with the json result that's not blank?
I also want to add the {variable names} into the CarsModel carsModel new CarsModel( {variable name} {variable name} );.
for (int i = 0; i < jsonMainNode.length(); i++) {
JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
// Get the keys in the JSON object
Iterator<?> keys = jsonChildNode.keys();
while (keys.hasNext()) {
// Get the key
String key = (String)keys.next();
String objValue = jsonChildNode.getString(key);
// check if empty
if (!objValue.isEmpty()) {
CarsModel carsModel new CarsModel(objValue);
}
}
}
This is what you need to do. The data you want is a json object inside a jsonArray
JSONObject jsonResponse = new JSONObject(JSON_STRING);
JSONArray jsonMainNode = jsonResponse.optJSONArray("server_response");
for (int i = 0; i < jsonMainNode.length(); i++) {
JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
variableX = jsonChildNode.getString("toyota");
variableY = jsonChildNode.getString("honda");
variableZ = jsonChildNode.getString("xyz");
// CarsModel thing using var x, y, z...
}
I have JSON code like above, as a response:
"candidates": [
{
"subtest1": "0.802138030529022",
"enrollment_timestamp": "1416850761"
},
{
"elizabeth": "0.802138030529022",
"enrollment_timestamp": "1417207485"
},
{
"elizabeth": "0.777253568172455",
"enrollment_timestamp": "1416518415"
},
{
"elizabeth": "0.777253568172455",
"enrollment_timestamp": "1416431816"
}
]
I try to get names from candidates array.
public void dataCheck(String text){
System.out.println("JSON response:");
System.out.println(text);
try {
JSONObject jsonRootObject = new JSONObject(text);
JSONArray jsonArray = jsonRootObject.optJSONArray("candidates");
for(int i=0; i < jsonArray.length(); i++){
JSONObject jsonObject = jsonArray.getJSONObject(i);
String subtest1 = jsonObject.optString("subtest1").toString();
}
} catch (JSONException e){
e.printStackTrace();
}
}
It is hard, because these values are in an array of an array and without identifier. Identifier is the exact value, so couldn't define variable in my code. I need only first value, like subtest1 in this example.
// Get the keys in the first JSON object
Iterator<?> keys = jsonObject.keys();
if (keys.hasNext()) {
// Get the key
String key = (String)keys.next();
String objValue = jsonObject.getString(key);
...
}