JSONObject in Android - java

Here i want to fetch the data from the json, but i am getting only first two objects value (25, 44) but the ids are 50,60 . I don't know whats wrong with this code.
Below is my response from the server:
{
"product": {
"25": {
"training": "First Name",
"taken": null,
"date": "1386737285",
"body":"http://abc.xyz.in/video1.mp4",
"image": "http://abc.xyz.in/video1.jpg"
},
"44": {
"training": "Second Name",
"taken": null,
"date": "1389951618",
"body":"http://abc.xyz.in/video2.mp4",
"image":"http://abc.xyz.in/video2.jpg"
},
"50": {
"training": "Third Name",
"taken": null,
"date": "1389971004",
"body":"http://abc.xyz.in/video3.mp4",
"image": "http://abc.xyz.in/video3.jpg"
},
"60": {
"training": "Fourth Name",
"taken": null,
"date": "1390003200",
"body": "http://abc.xyz.in/video4.mp4",
"image": "http://abc.xyz.in/video4.jpg"
}
}
}
Here is the code for fetching data from json:
public String[] getDataFromResponse(String jsonProfileResponse,String secondParam,
String attributeName ) {
String[] attributeValue = null;
try {
json = new JSONTokener(jsonProfileResponse).nextValue();
if (json instanceof JSONObject) {
JSONObject jsonObject = (JSONObject) json;
JSONObject jObj = jsonObject.getJSONObject(secondParam);
System.out.println(jObj);
Iterator<?> keys = jObj.keys();
List<String> listitems = new ArrayList<String>();
List<String> nids = new ArrayList<String>();
while (keys.hasNext()) {
nids.add(String.valueOf(keys.next()));
JSONObject jsonObj = jObj.getJSONObject(String.valueOf(keys
.next()));
System.out.println(jsonObj);
listitems.add(jsonObj.getString(attributeName));
}
attributeValue = listitems.toArray(new String[0]);
trainingId = nids.toArray(new String[0]);
}
} catch (JSONException ex) {
ex.printStackTrace();
}
return attributeValue;
}
Thanks for the considering...

Inside the hasNext you call twice keys.next()
So, instead of
nids.add(String.valueOf(keys.next()));
JSONObject jsonObj = jObj.getJSONObject(String.valueOf(keys.next()));
you have to do
String currentKey = String.valueOf(keys.next());
nids.add(currentKey);
JSONObject jsonObj = jObj.getJSONObject(currentKey);

String key="";
while (keys.hasNext()) {
key= keys.next()
JSONObject jsonObj = jObj.getJSONObject(String.valueOf(key));
nids.add(key));
System.out.println(jsonObj);
listitems.add(jsonObj.getString(attributeName));
}
use of key.next() twice is problem

because in JSONObject, the order of the keys is undefined.
#see: http://developer.android.com/reference/org/json/JSONObject.html#keys%28%29
try to sort your data on server, then response it in JSONArray

Related

Get data from nested JSON Object in Java Android

How I can get the "fields" objects 0,1,2,3,4 & only the "name" object string of every object using JSONOBJECT
[
{
"name": "Bank1",
"fields": {
"0": {
"name": "Email",
"slug": "email",
"type": "input"
},
"1": {
"name": "City",
"slug": "city",
"type": "input"
},
"2": {
"name": "Screenshot",
"slug": "screenshot",
"type": "file"
},
"3": {
"name": "Full Name",
"slug": "full-name",
"type": "input"
}
},
"status": "Active"
},
{
"name": "Bank2",
"fields": {
"0": {
"name": "Email",
"slug": "email",
"type": "input"
},
"1": {
"name": "City",
"slug": "city",
"type": "input"
},
"2": {
"name": "Screenshot",
"slug": "screenshot",
"type": "file"
},
"4": {
"name": "Submitted Date",
"slug": "submitted-date",
"type": "calendar"
}
},
"status": "Active"
}
]
& this is what I try to done
public void onResponse(String response) {
try {
JSONArray jsonArray = new JSONArray(response);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
String p_name = jsonObject.getString("name");
JSONObject jo = jsonObject.getJSONObject("fields");
String j1 = jo.getString("0");
if (!j1.isEmpty()){
JSONObject jo1 = jo.getJSONObject("0");
String f_name1 = jo1.getString("name");
Log.d("Field1.", f_name1);
}
}}catch block...
but the problem is, it gives me value of the object null like [value 4 is null] cuz there is no object for 4 in the first object of fields. please help me solve this prob, appreciate your answers thankyou :)
You can use keys() iterator of json object & loop on it using while (keys.hasNext())
For your example, it would look something like this:
private void parseJson(String response) {
try {
JSONArray jsonArray = new JSONArray(response);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
JSONObject jo = jsonObject.getJSONObject("fields");
Iterator<String> keys = jo.keys();
while (keys.hasNext()) {
String key = keys.next();
JSONObject jo1 = jo.getJSONObject(key);
String f_name1 = jo1.getString("name");
Log.d("Field1.", f_name1);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
There are some problems with get all keys properly in my IDE/JDK11, so I decided to loop over an ArrayList, basing on #MayurGajra solution, ex:
private static List<List<String>> parseJson(String response) throws JSONException {
JSONArray jsonArray = new JSONArray(response);
List<List<String>> result = new ArrayList<>();
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
JSONObject jo = jsonObject.getJSONObject("fields");
List<Object> list = new ArrayList<>();
jo.keys().forEachRemaining(list::add);
List<String> subList = new ArrayList<>();
for (Object o : list) {
String key;
if (isString(o))
key = (String) o;
else
continue;
JSONObject jo1 = jo.getJSONObject(key);
String f_name1 = jo1.getString("name");
subList.add(f_name1);
}
result.add(subList);
}
return result;
}
private static boolean isString(Object o) {
try {
String result = (String) o;
} catch (ClassCastException e) {
return false;
}
return true;
}
The result obtained after processing the above json is as follows:
[[Email, City, Screenshot, Full Name], [Email, City, Screenshot, Submitted Date]]
but it have not to be a List of Lists ;)
-- edit --
To get only first list of elements labeled "name":
try {
System.out.println(parseJson(yourJsonAsString).get(0).toString());
} catch (JSONException e) {
System.out.println("JSONException:" + e.getMessage());
}
The result of above is:
[Email, City, Screenshot, Full Name]

How to save data from textfields to json file?

how to save data from our textfields. For example i want to get this:
[
{
"Patient": {
"name": "John",
"surname": "Cena"
}
},
{
"Patient2": {
"name": "Roger",
"surname": "Federer"
}
}
]
And it was my try:
JSONObject obj = new JSONObject();
obj.put("imie", field1.getText());
obj.put("nazwisko", field2.getText());
try (FileWriter Data = new FileWriter("Data.JSON")) {
Data.write(obj.toJSONString());
Data.write(obj1.toJSONString());
} catch (IOException e1) {
e1.printStackTrace();
}
but i dont get "Patient2" and it overwriting my first patient if i press save button instead of add new one.
You should be using JSONArray to store several JSONObject instances:
// build object
JSONObject obj = new JSONObject();
obj.put("name", field1.getText());
obj.put("surname", field2.getText());
// build "patient"
JSONObject patient = new JSONObject();
patient.put("patient", obj);
// build another object
JSONObject obj1 = new JSONObject();
obj1.put("name", "Roger");
obj1.put("surname", "Federer");
// build another patient
JSONObject patient1 = new JSONObject();
patient1.put("patient1", obj1);
// create array and add both patients
JSONArray arr = new JSONArray();
arr.put(patient);
arr.put(patient1);
try (FileWriter Data = new FileWriter("Data.JSON")) {
Data.write(arr.toString(4)); // setting spaces for indent
} catch (IOException e1) {
e1.printStackTrace();
}
This code produces JSON:
[
{
"patient": {
"surname": "Doe",
"name": "John"
}
},
{
"patient1": {
"surname": "Federer",
"name": "Roger"
}
}
]

I am getting HTTP response string like below. I want subject_id and status string from response string

Response string is like this:
{
"images": [
{
"transaction": {
"status": "success",
"topLeftX": 325,
"topLeftY": 451,
"gallery_name": "Ironman",
"subject_id": "Tony",
"confidence": 0.99414,
"height": 630,
"width": 630,
"face_id": 1,
"quality": 1.75477
},
"candidates": [
{
"subject_id": "Tony",
"confidence": 0.99414,
"enrollment_timestamp": "1487644861022"
},
{
"subject_id": "Tony",
"confidence": 0.99414,
"enrollment_timestamp": "1487644876280"
}
]
}
]
}
I tried this code but not working..
JSONArray arr = new JSONArray(response);
JSONObject jObj = arr.getJSONObject(0);
String status = jObj.getString("status");
String message = jObj.getString("subject_id");
Use json simple lib
JSONObject json = new JSONObject(yourString);
JSONArray images = json.getJSONArray("images");
and you can loop throw this array
for (int i = 0; i < images.length(); i++) {
JSONObject o = images.getJSONObject(i);
....
}
You can use GSON to parse JSON Strings. If you just want the first object of the images array you can use this code:
JsonParser jsonParser = new JsonParser();
JsonObject obj = jsonParser.parse(responseString).getAsJsonObject();
JsonArray images = obj.getAsJsonArray("images");
String subjectId = images.get(0).getAsJsonObject().get("transaction")
.getAsJsonObject().get("subject_id").getAsString();
You can create pojo class for response
Also you can use GSON library for get response string.
use this
#Override
protected void onPostExecute(String result) {
JSONObject jsonobj;
// TODO Auto-generated method stub
super.onPostExecute(result);
if (result != null) {
if (result.equals("failure")) {
Toast.makeText(context, "Check your Username or Password", Toast.LENGTH_LONG).show();
dialog.dismiss();
} else {//ths is getting data for vehicl_list_unread_count code, client id,restapi_key
try {
Log.d(TAG, "onPostExecute: this inner of post" + getcontent_for_validate);
jsonobj = new JSONObject(getcontent_for_validate);
System.out.println("this is get content" + jsonobj.toString()); JSONArray array = jsonobj.getJSONArray("images");for (int i = 0; i < array.length(); i++) {
JSONArray transaction = array.getJSONObject(i).getJSONArray("transaction");for (int i = 0; i < array.length(); i++)
String status = transaction.getJSONObject(i).getString("status");
Password = editText_password.getText().toString();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
} else {
dialog.dismiss();
Toast.makeText(context, "Check net connection", Toast.LENGTH_LONG).show();
}
}
You tried
JSONArray arr = new JSONArray(response);
but you should
JSONObject arr = new JSONObject(response);
Because your main json is json object, not JSONArray

how to read values from jsonarray?

This is Json file.
{
"paging": {
"next_offset": 100,
"total": 247,
"limit": 100
},
"body_stats": [
{
"weight": 208.0,
"id": "13500547638911",
"date": "2012-10- 12T15:12:50Z",
"user_id": "13499829320503",
"bmr": 2723.328,
"bmi": 28.2067901234568
},
{
"resting_heart_rate": 65.0,
"weight": 135.0,
"id": "1b5kegg00 00js2p5pfmg000000",
"date": "2013-04- 15T00:44:12Z",
"user_id": "13589643116210",
"girths": {
"abdomen": 30.0,
"waist": 30.0
}
}
]
}
I want to read values from this json,
try{
Object obj = parser.parse(new FileReader("D:/jdemo.json"));
JSONObject jsonObject = (JSONObject) obj;
JSONArray companyList = (JSONArray)jsonObject.get("body_stats");
Iterator<Object> iterator = companyList.iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
}
Output:
{
"id": "13500547638911",
"bmr": 2723.328,
"weight": 208.0,
"bmi": 28.2067901234568,
"user_id": "13499829320503",
"date": "2012-10-12T15:12:50Z"
},
{
"id": "1b5kegg0000js2p5pfmg000000",
"weight": 135.0,
"girths": {
"abdomen": 30.0,
"waist": 30.0
},
"user_id": "13589643116210",
"date": "2013-04-15T00:44:12Z",
"resting_heart_rate": 65.0
}
But I want to read "girths"{" ",""} from this how can I read girths{} value?
This is an approach.
JsonElement jsonElement = new JsonParser().parse(new FileReader("D:/jdemo.json"));
JsonObject jsonObject = jsonElement.getAsJsonObject();
JsonArray jsonArray = jsonObject.getAsJsonArray("body_stats");
for(JsonElement body_stats : jsonArray) {
JsonElement girths = body_stats.getAsJsonObject().get("girths");
if(griths !=null) {
//The logic
}
}
"girths" should be another JSONObject, so I guess
.getJSONObject(2).get("girths");
on your JSONArray
try{
Object obj = parser.parse(new FileReader("D:/jdemo.json"));
JSONObject jsonObject = (JSONObject) obj;
JSONArray companyList = (JSONArray)jsonObject.get("body_stats");
Iterator<JSONObject> iterator = companyList.iterator();
while (iterator.hasNext()) {
JSONObject jsonObject = iterator.next();
Object object = jsonObject.get("girths");
if(object != null){
JSONObject girths = (JSONObject )object ;
System.out.println(girths);
}
}
}

JSON optString does not get the picture url

The obj.optString("picture") does not seem to get the picture url .jpeg as a string.
public static List<Photo> getPictures(AuthProvider provider, String source, String type) {
List<Photo> photos = new LinkedList<Photo>();
if (provider.getProviderId() == Constants.FACEBOOK) {
final String BASE_URL_FACEBOOK = "https://graph.facebook.com/";
String url = BASE_URL_FACEBOOK + source + "/feed";
try {
Response response = provider.api(url, MethodType.GET.toString(), null, null, null);
Log.d("AndroidAppPhotoUtil", "Status " + response.getStatus() + " returned by facebook get query " + url);
if (response.getStatus() == 200) {
String respStr = response.getResponseBodyAsString(Constants.ENCODING);
JSONObject resp = new JSONObject(respStr);
JSONArray data = resp.optJSONArray("data");
if (data != null)
for (int i = 0; i < data.length(); i++) {
JSONObject obj = data.getJSONObject(i);
Photo p = new Photo();
p.setId(obj.optString("id"));
p.setPicture(obj.optString("picture"));
if (isEmpty(type) || type.equals(obj.optString("type"))) {
photos.add(p);
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
return photos;
}
.
"id": "466138393436802_466165356767439",
"from": {
"name": "Dimitri Nicolopoulos",
"id": "100004358376630"
},
"to": {
"data": [
{
"name": "My Test Event",
"start_time": "2012-11-13",
"location": "Saewrreritvh",
"id": "466138393436802"
}
]
},
"picture": "http://photos-a.ak.fbcdn.net/hphotos-ak-ash3/533694_123231957832083_231056016_s.jpg",
"link": "http://www.facebook.com/photo.php?fbid=123231957832083&set=oa.160219667456793&type=1&relevant_count=1",
"icon": "http://static.ak.fbcdn.net/rsrc.php/v2/yz/r/StEh3RhPvjk.gif",
I added put your JSON code inside a '{' and a '}' and I did this:
String respStr = "{\"id\":\"466138393436802_466165356767439\",\"from\":{\"name\":\"Dimitri Nicolopoulos\",\"id\":\"100004358376630\"},\"to\":{\"data\":[{\"name\":\"My Test Event\",\"start_time\":\"2012-11-13\",\"location\":\"Saewrreritvh\",\"id\":\"466138393436802\"}]},\"picture\":\"http://photos-a.ak.fbcdn.net/hphotos-ak-ash3/533694_123231957832083_231056016_s.jpg\",\"link\":\"http://www.facebook.com/photo.php?fbid=123231957832083&set=oa.160219667456793&type=1&relevant_count=1\",\"icon\":\"http://static.ak.fbcdn.net/rsrc.php/v2/yz/r/StEh3RhPvjk.gif\"}";
JSONObject resp = new JSONObject(respStr);
System.out.println(resp.get("picture"));
This works. Also, your data is always null. The "data" is actually under the "to" key. So you can do
String respStr = "{\"id\":\"466138393436802_466165356767439\",\"from\":{\"name\":\"Dimitri Nicolopoulos\",\"id\":\"100004358376630\"},\"to\":{\"data\":[{\"name\":\"My Test Event\",\"start_time\":\"2012-11-13\",\"location\":\"Saewrreritvh\",\"id\":\"466138393436802\"}]},\"picture\":\"http://photos-a.ak.fbcdn.net/hphotos-ak-ash3/533694_123231957832083_231056016_s.jpg\",\"link\":\"http://www.facebook.com/photo.php?fbid=123231957832083&set=oa.160219667456793&type=1&relevant_count=1\",\"icon\":\"http://static.ak.fbcdn.net/rsrc.php/v2/yz/r/StEh3RhPvjk.gif\"}";
JSONObject resp = new JSONObject(respStr);
JSONObject data = (JSONObject) resp.getJSONObject("to").getJSONArray("data").get(0);
System.out.println(data);

Categories