I have a problem with json.
I get this response from server:
{"TESTS":true,"TESTS_VIEW":true,"ORDER":true,"PARAMETERS":true,"VIEW":true}
How can I save this data in array or something else to have schema: key - value?
Hmm, not sure I understand why you want this. A JSONObject gives you exactly that, have a look at JSONObject.get():
JSONObject json = new JSONObject(yourjsonstringfromserver);
boolean tests = json.getBoolean("TESTS");
Still, if you want to iterate over all values you can do like this:
Map<String, Object> map = new HashMap<String, Object>();
Iterator<String> keys = json.keys();
for(String key : keys) {
try {
Object value = json.get(key);
map.put(key, value);
}
catch (JSONException e) {
// Something went wrong!
}
}
JSONObject object = YourObjectHere;
Map<String,Boolean> dict = new HashMap<String,Boolean>();
Iterator it = object.keyes();
while( it.hasNext() ){
String key = it.next();
String value = object.get(key);
dict.put( key, value );
}
Solution, more or less. //Written without checking in IDE so may contain bugs/errors
JSONObject json = new JSONObject(response);
json.getInt(keyA);
json.getString(keyB);
and etc;
You can using this function with httpResponse is your json string:
public static YourModel parseJson(String httpResponse) {
YourModel objObject = new YourModel();
try {
JSONArray jsonArrayData = new JSONArray(httpResponse);
if (jsonArrayData.length() >= 1) {
for (int i = 0; i < jsonArrayData.length(); i++) {
JSONObject object = new JSONObject(jsonArrayData.get(0));
// Setting value by key json
objObject.setAtrr(object.getString("YourKey"));
}
}
} catch (JSONException e) {
e.printStackTrace();
return null;
}
return objObject;
}
Related
I try to parse the response and try to get the Date object from the response but unable to get it. Could anyone tell me how can i get the Date object.
{
"flag":"success",
"msg":[
{
"2018-10-01":{
"date":"2018-10-01",
"login_time":"1538393123",
"logout_time":"",
"logout_message":"",
"lock_time":"1538393236,1538393671,1538393764",
"unlock_message":"testing,testing,break time",
"unlock_time":"1538393363,1538393680,1538395633"
}
},
{
"2018-10-03":{
"date":"2018-10-03",
"login_time":"1538548533",
"logout_time":"",
"logout_message":"",
"lock_time":"1538560561,1538561016,1538561260,1538561881",
"unlock_message":"hey,gggg,gggg5555,fd",
"unlock_time":"1538560617,1538561100,1538561273,1538566017"
}
}
]
}
Try this
try {
JSONObject jsonObject = new JSONObject(jsonString);
JSONArray jsonArray = jsonObject.getJSONArray("msg");
for(int i=0;i < jsonArray.length();i++)
{
JSONObject obj = jsonArray.getJSONObject(i);
Iterator<?> keys = obj.keys();
while( keys.hasNext() ) {
String key = (String)keys.next();
if(obj.get(key) instanceof JSONObject) {
JSONObject dateObj = (JSONObject) obj.get(key);
String DATE = dateObj.getString("date");
Log.d("DATE",DATE);
}
}
}
} catch (JSONException e) {
e.printStackTrace();
}
Here's a small demo code. Please reuse the SimpleDateFormat if you're using it more often.
Date date = new SimpleDateFormat("yyyy-MM-dd").parse(object.optJSONArray("msg").optJSONObject(i).optString("date","").getTime();
var object = {"flag":"success","msg":[{"2018-10-01":{"date":"2018-10-01","login_time":"1538393123","logout_time":"","logout_message":"","lock_time":"1538393236,1538393671,1538393764","unlock_message":"testing,testing,break time","unlock_time":"1538393363,1538393680,1538395633"}},{"2018-10-03":{"date":"2018-10-03","login_time":"1538548533","logout_time":"","logout_message":"","lock_time":"1538560561,1538561016,1538561260,1538561881","unlock_message":"hey,gggg,gggg5555,fd","unlock_time":"1538560617,1538561100,1538561273,1538566017"}}]};
var msg = object.msg;
var dateobjects = []; // to store the date objects
//to go through the msg array items
for(var i = 0; i < msg.length; i++)
{
let current = msg[i];
for(var prop in current)
dateobjects.push(current[prop]);
}
// Print date objects in console
console.log(dateobjects);
I have a json object as below
{
"Book1":{"Title1":"Cost1","Title2":"Cost2"},
"Book2":{"Title3 ":"Cost3"},
"Book3":{"Title4 ":"Cost4","Title5 ":"Cost5"},
"Book4":{"Title6":"Cost6","Title7”:”Cost7","Title8”:”Cost8"}
}
I want to retrieve all the values of "Titles" without any keywords i.e I would like to have {Title1,Title2,Title3,Title4,...} in an array.
Below is my code to retrieve based on Book name but now I need to retrieve all the values
List<String> books=new ArrayList<String >();
try {
JSONObject obj = new JSONObject(loadJSONFromAssetArea());
JSONObject bookJson = obj.getJSONObject("Book1");
Iterator<String> keys= bookJson.keys();
do
{
String keyValue = (String)keys.next();
JSONArray specTitle = obj.getJSONArray(keyValue);
for (int i = 0; i < specTitle.length(); i++) {
books.add(specTitle.get(i).toString());
}
}while(keys.hasNext());
} catch (JSONException e) {
e.printStackTrace();
}
I am not getting how to get with out passing key values to json object .
Kindly help.
Thanks in advance
Try This is Working
JSONObject jsonObject = new JSONObject(loadJSONFromAssetArea());
List<String> books=new ArrayList<String >();
try {
Iterator iteratorObj = jsonObject.keys();
while (iteratorObj.hasNext())
{
String getJsonObj = (String)iteratorObj.next();
System.out.println("Book No.: " + "------>" + getJsonObj);
JSONObject jo_inside = jsonObject.getJSONObject(getJsonObj);
//JSONObject jo_inside = new JSONObject((String) iteratorObj.next());
Iterator<String> keys = jo_inside.keys();
while (keys.hasNext())
{
String key = keys.next();
String value = jo_inside.getString(key);
Log.v("Book Title key", key);
Log.v("Book Name value", value);
books.add(jo_inside.getString(key));
}
}
} catch (JSONException e) {
e.printStackTrace();
}
NOTE
Your GIVEN Json is not Valid.
Book1,Book2.. are DYNAMIC/UNKNOWN.
Use Iterator in this way.
Try this way,
JSONObject jOBJ= new JSONObject(loadJSONFromAssetArea());
Iterator iteratorObj = jOBJ.keys();
while (iteratorObj.hasNext())
{
String getJsonObj = (String)iteratorObj.next();
System.out.println("Key: " + Key + "------>" + getJsonObj); // print Book1,Book2..
// Now your work
}
If you want to parse this
{
"Book1":{"Title1":"Cost1","Title2":"Cost2"},
"Book2":{"Title3 ":"Cost3"},
"Book3":{"Title4 ":"Cost4","Title5 ":"Cost5"},
"Book4":{"Title6":"Cost6","Title7”:”Cost7","Title8”:”Cost8"}
}
you can use this code to parse the json object,
List<String> books = new ArrayList<String>();
try {
JSONObject obj = new JSONObject(loadJSONFromAssetArea());
JSONObject bookJson, innerObject;
Iterator<String> keys = obj.keys();
do {
String keyValue = (String) keys.next();
if (obj.get(keyValue) instanceof JSONObject) {
bookJson = obj.getJSONObject(keyValue);
Iterator<?> innerKeys = bookJson.keys();
while (innerKeys.hasNext()) {
String innerKey = (String) innerKeys.next();
innerObject = bookJson.getJSONObject(innerKey);
books.add(innerObject.getString(innerKey));
}
}
} while (keys.hasNext());
} catch (JSONException e) {
e.printStackTrace();
}
I have a json with colon between the strings, and I'm not sure how can I parse it. I know that I don't have an array in the json, but I'm not sure how can I get the values...
{
"config": {
"network": {
"hni:21407" : "num:[INTNUM]",
"hni:311490" : "num:044[INTNUM]"
}
}
}
This is what I'm trying, but I never go through the loop for, and not really sure if I need it.
JSONObject obj = new JSONObject(netWorkJson);
String arr = obj.optString("network");
for(int i = 0; i < arr.length(); i++) {
String hni = obj.getString("hni");
String num = obj.getString("num");
}
Thanks in advance
You first need to parse the inner json object "network", after that you can loop over it's keys and get the values for them one by one:
private void parseJSON(String netWorkJson) throws JSONException {
JSONObject obj = new JSONObject(netWorkJson);
JSONObject config = obj.getJSONObject("config");
JSONObject network = config.getJSONObject("network");
Iterator<?> keys = network.keys();
while(keys.hasNext()) {
String key = (String) keys.next();
String value = network.getString(key);
}
}
Beauty of this is that it will also work if you had 100 hni values for example, and that you don't have to get them one by one.
network is JSONObject instead of JSONArray, so no need to use for-loop for getting value from it.just use do it as:
JSONObject obj = new JSONObject(netWorkJson);
// get network JSONObject from obj
JSONObject network=obj.getJSONObject("network");
// get both values from network object
String strHni=network.optString("hni:21407");
String strNum =network.optString("hni:311490");
JSONObject message = new JSONObject(config);
String value=message.getJSONObject("network").getString("hni:21407")
Try This
try {
JSONObject jsonObject = new JSONObject("config");
JSONArray jsonArray = jsonObject.getJSONArray("network");
for(int i =0;i<jsonArray.length();i++){
JSONObject jsonObject1 = jsonArray.getJSONObject(i);
String hni21407 = jsonObject1.getString("hni:21407");
String hni311490 = jsonObject1.getString("hni:311490");
}
} catch (JSONException e) {
e.printStackTrace();
}
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.
Currently, I'm having a minor trouble trying to get the string data from the jsonArray, however, I'm unable to get the value . I've got the data in the json object Example:
{
"lot":[
{
"id":"271",
"lot_date":"2015-05-25"
}
],
"numb3":[
{
"id":"675",
"lot_date":"2015-05-25"
}
],
"num4":[
{
"id":"676",
"lot_date":"2015-05-25"
}
],
"result":"OK"
}
The data above is stored in the JsonObject jsonobj. And what I want to do is to check if the JSON array JSONArray lot6 = jsonobj.optJSONArray("lot6"); contains the values or not , and if it's not null get the string data. However, even the data contains in the lot6 array, the result is null.
JSONArray lot6 = jsonobject.optJSONArray("lot6");
Log.d("LOT6",lot6+"");
if (lot6 != null) {
jsonarry2 = jsonobject.getJSONArray("lot6");
//3.if not null get the string data from the
for (int i = 0; i < jsonarry2.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
jsonobject = jsonarry2.getJSONObject(i);
ListData worldpop = new ListData();
worldpop.set_date(jsonobject.optString("lot_date"));
worldpop.set__id(jsonobject.optString("id"));
world.add(worldpop);
}
//5. test this part of the variable
String lotdate = world.get(0).get_date();
String lotid = world.get(0).get__id();
Hi please check Not lot6 its lot. please folloe below formate to get out out.
String s="{\"lot\":[{\"id\":\"271\",\"lot_date\":\"2015-05-25\"}],\"numb3\":[{\"id\":\"675\",\"lot_date\":\"2015-05-25\"}],\"num4\":[{\"id\":\"676\",\"lot_date\":\"2015-05-25\"}],\"result\":\"OK\"} ";
try{
JSONParser parser = new JSONParser();
JSONObject json = (JSONObject) parser.parse(s);
String arr[]={"lot","numb3","num4"};
for(int i=0;i<json.size()-1;i++){
JSONArray ja=(JSONArray)json.get(arr[i]);
for(int j=0;j<ja.size();j++){
JSONObject jo1=(JSONObject) ja.get(j);
System.out.println("lot_date: "+jo1.get("lot_date")+" Id "+jo1.get("id"));
}
// System.out.println(ja);
}
System.out.println(json.get("result"));
}catch (Exception e) {
System.out.println(e);
}