JSON optString does not get the picture url - java

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);

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]

Output a JSON string with previous Format in JAVA

I have this JSON flat file and I need to change the value of clientCode
{
"clientNumber": "Test",
"clientCode": "12345",
"clientReference": "JSON Testing",
"billingCode":"90code",
"clienttructure": "new, test, Java",
"site": "sampleStore",
"siteDestination": "EU",
}
I tried to change clientCode value and check the return of the method.
I'm Using Java
String jsonName = "clientCode ";
String jsonValue = "new Value";
String JSONSource = path;
public String put(String jsonName, String jsonValue, String JSONSource) {
String jsonString = null;
try {
Object obj = parser.parse(new FileReader(JSONSource));
org.json.simple.JSONObject jsonObject = (org.json.simple.JSONObject) obj;
jsonObject.put(jsonName, jsonValue);
jsonString = jsonObject.toJSONString();
} catch (IOException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
}
return jsonString;
}
Actual output is:
{ "billingCode":"90code", "clientCode": "new Value","clientNumber": "Test","clientReference": "JSON Testing",.....}
Expected output should be :
{
"clientNumber": "Test",
"clientCode": "new Value",
"clientReference": "JSON Testing",
"billingCode":"90code",
"clienttructure": "new, test, Java",
"site": "sampleStore",
"siteDestination": "EU",
}
Try this...
JSONObject jsonobject = new JSONObject(response);
jsonobject .remove("clientCode");
JSONObject updateValue = new JSONObject(updateValue);
String UpdatedValue = updateValue.getString("clientCode");
jsonobject .put("clientCode", UpdatedValue);

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

JSONObject in Android

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

How to loop through json data in android

As mentioned in the title. How can I loop through my json data that I am getting from server. My getting this kind of json data
{
"tag":"home",
"success":1,
"error":0,
"uid":"4fc8f94f1a51c5.32653037",
"name":"Saleem",
"profile_photo":"http:\/\/example.info\/android\/profile_photos\/profile1.jpg",
"places":
{
"place_photo":"http:\/\/example.info\/android\/places_photos\/place1.jpg",
"created_at":"2012-06-02 00:00:00",
"seeked":"0"
}
}
{
"tag":"home",
"success":1,
"error":0,
"uid":"4fc8f94f1a51c5.32653037",
"name":"Name",
"profile_photo":"http:\/\/example.info\/android\/profile_photos\/profile1.jpg",
"places":
{
"place_photo":"http:\/\/example.info\/android\/places_photos\/place1.jpg",
"created_at":"2012-06-02 00:00:00",
"seeked":"0"
}
}
{
"tag":"home",
"success":1,
"error":0,
"uid":"4fc8f94f1a51c5.32653037",
"name":"Name",
"profile_photo":"http:\/\/example.info\/android\/profile_photos\/profile1.jpg",
"places":
{
"place_photo":"http:\/\/example.info\/android\/places_photos\/place1.jpg",
"created_at":"2012-06-02 00:00:00",
"seeked":"0"
}
}
here is where I am getting my json data
public class Home extends Activity {
Button btnLogout;
ScrollView svHome;
UserFunctions userFunctions;
LoginActivity userid;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
userid = new LoginActivity();
svHome = (ScrollView)findViewById(R.id.svHome);
setContentView(R.layout.home);
userFunctions = new UserFunctions();
/***********************************************************/
//here is where my above mentioned json data is
JSONObject json = userFunctions.homeData();
try {
if(json != null && json.getString("success") != null) {
//login_error.setText("");
String res = json.getString("success");
//userid = json.getString("uid").toString();
if(Integer.parseInt(res) == 1) {
//currently this only shows the first json object
Log.e("pla", json.toString());
} else {
//login_error.setText(json.getString("error_msg"));
}
} else {
Toast.makeText(getBaseContext(), "No data", Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
/*******************************************************/
}
}
Update
After make changes accroding to the link given in the answer. Here are my changes
/***********************************************************/
JSONObject json = userFunctions.homeData();
String jsonData = json.toString();
try {
if(json != null && json.getString("success") != null) {
//login_error.setText("");
String res = json.getString("success");
//userid = json.getString("uid").toString();
if(Integer.parseInt(res) == 1) {
JSONArray jsonArray = new JSONArray(jsonData);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
Log.e("Object", jsonObject.getString("places"));
//Log.i(ParseJSON.class.getName(), jsonObject.getString("text"));
}
Log.e("pla", json.toString());
} else {
//login_error.setText(json.getString("error_msg"));
}
} else {
Toast.makeText(getBaseContext(), "No data", Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
Please look over the link
http://www.androidhive.info/2012/01/android-json-parsing-tutorial/
an if possible made the changes in json, as there is no array braces "[" "]" in json and you need that to itrate in loop
json should be like that
{
"arrayKey": [
{
"tag": "home",
"success": 1,
"error": 0,
"uid": "4fc8f94f1a51c5.32653037",
"name": "Saleem",
"profile_photo": "http://example.info/android/profile_photos/profile1.jpg",
"places": {
"place_photo": "http://example.info/android/places_photos/place1.jpg",
"created_at": "2012-06-02 00:00:00",
"seeked": "0"
}
},
{
"tag": "home",
"success": 1,
"error": 0,
"uid": "4fc8f94f1a51c5.32653037",
"name": "Saleem",
"profile_photo": "http://example.info/android/profile_photos/profile1.jpg",
"places": {
"place_photo": "http://example.info/android/places_photos/place1.jpg",
"created_at": "2012-06-02 00:00:00",
"seeked": "0"
}
}
]
}
You could use the json libraries like the following:
import org.json.JSONArray;
import org.json.JSONObject;
which allows you to read json data into array like this:
JSONArray jsonArray = new JSONArray([your json data]);
Try this tutorial: http://www.vogella.com/articles/AndroidJSON/article.html
one other way I'll recommend is Use GSON library, It is easy end pain less. for well formatted Json
As your logcat states, you're trying to convert a JSONObject to a JSONArray:
org.json.JSONException: Value {"uid":"4fc8f94f1a51c5.32653037","places":{"place_photo":"http://example.info/android/places_photos/place1.jpg","created_at":"2012-06-02 00:00:00","seeked":"0","longitude":"24.943514","latitude":"60.167112"},"error":0,"success":1,"tag":"home","profile_photo":"http://example.info/android/profile_photos/profile1.jpg","name":"Zafar Saleem"} of type org.json.JSONObject cannot be converted to JSONArray
Try to debug the code - find out where the exception is thrown, and make a JSONObject there instead of a JSONArray.

Categories