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);
...
}
Related
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
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.
The is my JSON string .
{
"server_response":
{
"source_response" :
[
{"stoppage_name":"sealdah","bus_no":"43#230#234/1#30_A"}
] ,
"destination_response" :
[
{"stoppage_name":"howrah","bus_no":"43#234/1#30_A"}
]
}
}
I think there would be a '[' after "server_response" , but not sure .
I am trying to retrieve the data but the code is not working .
try {
jsonObject = new JSONObject(json_string);
jsonArray = jsonObject.getJSONArray("server_response");
int count=0 ;
String stoppage,busno;
while(count<1)
{
JSONArray JA = jsonArray.getJSONArray(0);
JSONObject JO = JA.getJSONObject(count);
stoppage = JO.getString("stoppage_name");
busno = JO.getString("bus_no");
Toast.makeText(getApplicationContext(),"Stoppage ="+ stoppage+" Bus no =" +busno, Toast.LENGTH_LONG).show();
count ++;
}
} catch (JSONException e) {
e.printStackTrace();
}
Where I am making wrong . I am new to JSON and Android.
jsonObject = new JSONObject(json_string);
jsonServerObject = jsonObject.getJSONObject("server_response");
jsonSourceArray = jsonServerObject.getJSONArray("source_response");
jsonDestinationArray = jsonServerObject.getJSONArray("destination_response");
//Iterate your 2 arrays
server_response is not a JSONArray, it's a JSONObject. Because array have numeric key, not string.
i have already answer this type of question .. what you have to do .. use multiple for loop to getting value inside array under array.
this is srceen shots
JSONArray objJson = new JSONArray(strJSONData);
System.out.println("AppUserLogin:"+objJson);
// Parsing json
if(arrJson.length()>0)
{
for (int i = 0; i < objJson.length(); i++) {
try {
JSONObject objprod = arrJson.getJSONObject(i);
HashMap<String, String> MaplistTemp = new HashMap<String, String>();
MaplistTemp.put("replyCode",
objprod.getString("replyCode"));
MaplistTemp.put("replyCode",
objprod.getString("replyCode"));
JSONArray objproduct_var = new JSONArray(objprod.getString("LearningStandards"));
if ((objproduct_var.length()) > 0) {
for (int k = 0; k < objproduct_var.length(); k++) {
JSONObject objprodvar = objproduct_var
.getJSONObject(k);
MaplistTemp
.put("1",
objprodvar
.getString("1"));
MaplistTemp
.put("2",
objprodvar
.getString("2"));
MaplistTemp
.put("3",
objprodvar
.getString("3"));
MaplistTemp
.put("4",
objprodvar
.getString("4"));
}
}
// sub_categorys_details.add(sub_cat_det);
medpostList.add(MaplistTemp);// adding to final hashmap
} catch (JSONException e) {
e.printStackTrace();
}
}
}
Try this , and {} = object [] = array
try{
jsonObject = new JSONObject(json_string);
injsonObject = jsonObject.getJSONObject("server_response");
jsonArray = injsonObject.getJSONArray("source_reponse");
}catch(Exception e){}
sonArray = jsonObject.getJSONArray("server_response");
Here you are trying to access server_response as an array. It isn't an array. "server_response" is the key to the nested object:
{
"source_response" :
[
{"stoppage_name":"sealdah","bus_no":"43#230#234/1#30_A"}
] ,
"destination_response" :
[
{"stoppage_name":"howrah","bus_no":"43#234/1#30_A"}
]
}
See? Thats not an array, tis a JSON object with two keys, each of them have an array as value.
I'm not very familiar with android or java but in plain old javascript you could try something like:
var sourceResp = jsonObject.server_response.source_response;
or
var sourceResp = jsonObject["server_response"]["source_response"];
That will produce an array with one item in it.
I hope this can get you going.
Hi guys i got a json string like
{
"Successful": true,
"Value": "{\"MesajTipi\":1,\"Mesaj\":\"{\\\"Yeni\\\":\\\"Hayır\\\",\\\"Oid\\\":\\\"3d9b81c9-b7b3-4316-8a73-ad4d54ee02a8\\\",\\\"OzelKod\\\":\\\"\\\",\\\"Adet\\\":1,\\\"ProblemTanimi\\\":\\\"999\\\",\\\"HataTespitYeri\\\":\\\"Montajda\\\",\\\"Tekrar\\\":\\\"Evet\\\",\\\"ResmiBildirimNo\\\":\\\"\\\",\\\"Malzeme\\\":\\\"5475ffdb-0bc0-49cb-9186-429c60dbf91b\\\",\\\"HataKodu\\\":\\\"c30df623-496b-4a62-ba16-493bd435ca33\\\",\\\"Tarih\\\":\\\"2016-04-16 10:34:00\\\",\\\"KayitNo\\\":\\\"1600010.2\\\"}\"}"
}
I need to get "Oid" value from this string.
I tried to get it with
Gson gson = new Gson();
JsonParser parse = new JsonParser();
JsonObject jsonobj = (JsonObject) parse.parse(snc);
String stroid = jsonobj.get("Oid").toString();
But it gives null referance exception ? Any idea how can i get the only Oid value ?
Edit
I already tried How to parse JSON in Java but still no succes
What i tried from this page :
String pageName = jsonObj.getJSONObject("Value").getJSONObject("Mesaj").getString("Oid");
lets say this is your JSON
{
"success":"ok",
"test" : [{"id" : "1" ,"name" : "first"}]
,"RPTF":
[{"cats":[{"id" : "1" ,"name" : "first"},
{"id" : "1" ,"name" : "first"},
{"id" : "2" ,"name" : "test"} ]
,"pics" : [{"id" : "12" ,"value" : "description" ,"src" : "http://citygram.ir" ,"visit" : "3" },
{"id" : "10" ,"value" : "description" ,"src" : "http://citygram.ir" ,"visit" : "3" } ]
}]
}
method number one (if you want to access "success")
public String jsonOne(String json, String target) {
String result;
try {
JSONObject jo = new JSONObject(json);
result = jo.getString(target);
} catch (JSONException e) {
return "";
}
return result;
}
you can simply call this method like this
jsonOne(String json, "success");
method number two (in case you want to access "id"s inside the "test")
public String[] jsonTwo(String json, String target0, String target1) {
String[] result;
result = new String[1];
try {
JSONObject jo = new JSONObject(json);
JSONArray ja = jo.getJSONArray(target0);
result = new String[ja.length()];
for (int i = 0; i < ja.length(); i++) {
JSONObject jojo = ja.getJSONObject(i);
result[i] = jojo.getString(target1);
}
} catch (JSONException e) {
}
return result;
}
you get an array String on call :
jsonTwo(String json, "test", "id");
method number three (let's say you want to access "value"s in side "pics")
public String[] jsonThree(String json, String target0, String target1,String target2) {
String[] result;
result = new String[1];
try {
JSONObject jo = new JSONObject(json);
JSONArray ja = jo.getJSONArray(target0);
JSONObject jojo=ja.getJSONObject(0);
JSONArray jaja=jojo.getJSONArray(target1);
result = new String[jaja.length()];
for (int i = 0; i < ja.length(); i++) {
JSONObject jojojo = jaja.getJSONObject(i);
result[i] = jojojo.getString(target2);
}
} catch (JSONException e) {
toast("Wrong");
}
return result;
}
on call :
jsonThree(String json, "RPTF", "pics", "value");
you can write more methods like this and just call them .
The problem is because of extra " " in the "Value" section of JSON, so it will be treated as String not an object. The better solution is to seek the source of the JSON to see why they added extra " " and clear that but if you don't have access the source I propose the following:
Replace:
String stroid = jsonobj.get("Oid").toString();
with:
String valueString = jsonobj.getString("Value");
jsonobj = new JSONObject(valueString);
String mesagString = jsonobj.getString("Mesaj");
jsonobj = new JSONObject(mesagString);
String stroid = jsonobj.getInt("Oid").toString();
I know how to parse json but I can not solve integer json field in this json. Because this json contain integer field(23254,23998).
Here my JSON
{
"status":"OK",
"alarms":{
"23254":[
{
"speed_limit":250,
"acc_limit":null,
"dcc_limit":null,
"idle_limit":null
}
],
"23998":[
{
"speed_limit":120,
"acc_limit":null,
"dcc_limit":null,
"idle_limit":null
}
]
}
}
try{
JSONObject j=new JSONObject("here put your response string");
JSONObject j1= j.getJSONObject("alarms");
ArrayList<String> arr=new ArrayList<String>();
Iterator iter = j1.keys();
while(iter.hasNext()){
String key = (String)iter.next();
arr.add(j1.getJSONArray(key).toString());
System.out.println("json"+j1.getJSONArray(key).toString());
}
}catch (JSONException e){
e.printStackTrace();
}
Parse the Json object like this way
JSONObject obj= new JSONObject(content);
Iterator iterator = obj.keys();
while(iterator.hasNext()){
String key = (String)iterator.next();
JSONObject object1 = obj.getJSONObject(key);
// get id from object1
String _pubKey = object1.optString("id");
}