When I run my app, In logcat, "Problem parsing the earthquake Json results
org.json.JSONException: No value for fields"
Could you check my JSON code..? I'm beginner of JSON Parsing, So I searched a lot inf But I'm not sure about my code.
public class Utils {
private static List<News> extractFromJson(String newsJSON) {
if (TextUtils.isEmpty(newsJSON)) {
return null;
}
List<News> news = new ArrayList<>();
try {
// Create a JSONObject from the JSON response string
JSONObject baseJsonResponse = new JSONObject(newsJSON);
JSONObject response = baseJsonResponse.getJSONObject("response");
JSONArray jsonArray = response.getJSONArray("results");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject currentNews = jsonArray.getJSONObject(i);
JSONObject fields = currentNews.getJSONObject("fields");
Drawable thumbnail = LoadImageFromUrl (fields.getString("thumbnail"));
String section = currentNews.getString("sectionName");
String title = currentNews.getString("webTitle");
String url = currentNews.getString("webUrl");
String date = currentNews.getString("webPublicationDate");
news.add(new News( section, title, url, date,thumbnail));
}
return news;
} catch (JSONException e) {
Log.e("Utils", "Problem parsing the news Json results", e);
}
return null;
}
private static Drawable LoadImageFromUrl(String imageurl) {
Drawable drawable = null;
InputStream inputStream = null;
try {
inputStream = new URL(imageurl).openStream();
drawable = Drawable.createFromStream(inputStream, null);
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
return drawable;
}
}
Try this to validate
Problem occur may be you dont have a field jsonobject in your json list. It may be not present in the some of other jsonobjects. So check if jsonobject has actual field jsonobject before parsing.
Use this condition whenever your json value might give null sometimes.
if(currentNews.has("fields"))
{
JSONObject fields = currentNews.getJSONObject("fields");
}
else
{
Log.d("JSON_TAG","NO FIELD JSON OBJECT");
}
Related
In my program, I am able to fetch all my text. But In my JSOn in a JSON Array there is another JSONArray which have image url. I am getting all my URL in JSON Array when I am using
JSONArray attachments = post.getJSONArray("itemimage");
but when loop is finished, I am getting nothing in my response. How can I replace my ImageView with URLs which is store in attatchment. My Code is here
private void parseResult(String result) {
try {
JSONObject response = new JSONObject(result);
JSONArray posts = response.optJSONArray("items");
GridItem item;
for (int i = 0; i < posts.length(); i++) {
JSONObject post = posts.optJSONObject(i);
String title = post.optString("itemname");
item = new GridItem();
item.setTitle(title);
JSONArray attachments = post.getJSONArray("itemimage");
if (null != attachments && attachments.length() > 0) {
JSONObject attachment = attachments.getJSONObject(0);
if (attachment != null)
item.setImage(attachment.getString(""));
}
mGridData.add(item);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
Um,i am 2 mins late post it out...cuz writing the demo for u.
The parse method you need is below,and you can use framework like Universal Image Loader to load the url to your imageView.
private String parseaaa(String jsonString) {
String imgUrl = "";
try {
JSONObject mJsonObject = new JSONObject(jsonString);
JSONArray mArray = mJsonObject.getJSONArray("items");
for (int i = 0; i < mArray.length(); i++) {
JSONObject object=mArray.getJSONObject(i);
imgUrl+=object.getString("itemimage")+"\n";
Log.i(TAG, imgUrl);
}
} catch (Exception e) {
// TODO: handle exception
}
return imgUrl;
}
BTW,just use JSONArray to load things between [] and JSONObject to load the obj... It's easy to do.
As I can see your JSON you should get JSONException at
JSONObject attachment = attachments.getJSONObject(0);
because your are creating object which is not present there, So I would suggest to simply extract String from your JSONArray and do your setImage stuff..
if (null != attachments && attachments.length() > 0) {
String image= (String) attachments.get(0);
//--- set your image here--//
}
I'm reading json and it works fine.
But it's failed to add resulting String into the ArrayList.
Any ideas why ?
Here is the code.
StuffPics class (updated):
public class StuffPics {
private String imageUrl;
public StuffPics() {
}
public String getImageUrl() {
return imageUrl;
}
public String setImageUrl(String imageUrl) {
return this.imageUrl;
}
#Override
public String toString() {
return "StuffPics = " + this.imageUrl;
}
}
Activity (updated):
private ArrayList<StuffPics> mylist;
...
protected void onPostExecute(String result) {
try{
String url="http://www.test.com";
JSONArray jsonarray = new JSONArray(result);
int lengthJsonArr = jsonarray.length();
for (int i = 0; i < lengthJsonArr; i++)
{
//build url
JSONObject jsonChildNode = jsonarray.getJSONObject(i);
String autcElement = jsonChildNode.optString("picUrl").toString();
String img= url + autcElement;
System.out.println("imageUrl"+img);
//create object and add it to the list
StuffPics pic = new StuffPics();
pic.getImageUrl();
System.out.print("PIC"+pic);
mylist.add(pic);
}
}
catch (Exception e) {
e.printStackTrace();
}
}
So, the first System.out shows strings, as they should be. Means json was read the right way.
But the second System.out shows nothing. Means I can't add strings into StuffPics pic. As the result ArrayList mylist is empty as well.
What am I doing wrong ?
Well pic is a custom object StuffPics .
You will need to override toString() in order to see something
for example:
#Override
public String toString() {
return "StuffPics = " + this.imageUrl;
}
also make sure mylist is initialized and you can adjust your code like this:
try{
String url="http://www.test.com";
JSONArray jsonarray = new JSONArray(result);
int lengthJsonArr = jsonarray.length();
for (int i = 0; i < lengthJsonArr; i++)
{
//build url
JSONObject jsonChildNode = jsonarray.getJSONObject(i);
String autcElement = jsonChildNode.optString("picUrl").toString();
String img= url + autcElement;
System.out.println("imageUrl"+img);
//create object and add it to the list
StuffPics pic = new StuffPics();
pic.setImageUrl(img);
System.out.print("PIC"+pic.toString());
mylist.add(pic);
}
}
catch (Exception e) {
e.printStackTrace();
}
You can use Gson
to view your custom objects.son is a Java library that can be used to convert Java Objects into their JSON representation.
simply convert your object to a json using:
String json = new Gson().Json(pic);
and print it using logs.
Replace this line:
System.out.print("PIC"+pic);
with that:
System.out.print("PIC"+pic.getImageUrl());
Your list is not empty, you are only not able to see the URL you added.
I am receiving a String response from the following #Override method
#Override
publc void onSuccess(String response) {
....
}
The conflict I am facing is that I do not know how to break up this response into key value pairings. This is an example of the response.
{"action":{"generic_message":"test generic message"},"domains":{"key_example_one":"https:/google.com","api_root_url":"https://test.com/new/0.2/json"},"page":null}}
I have attempted to convert the string to a JSONObject, and then adding the JSONObjects to a JSONArray.
JSONObject mJObj;
try {
mJObj = new JSONObject(response);
JSONArray mJArry = mJObj.getJSONArray("action");
for (int i = 0; i < mJArry.length(); i++) {
JSONObject newObj = mJArry.getJSONObject(i);
String test2 = newObj.getString("generic_example_for_all_platforms");
}
} catch (JSONException e) {
e.printStackTrace();
}
EDIT: I am getting JSON exception that JSONArray cannot be converted to JSONObject, for the following line.
JSONArray mJArry = mJObj.getJSONArray("action");
Thanks in advante
You do want to read more about JSON here.
The first thing to know is that {} is equal to a Json Object and [] is equal to a Json Array.
try {
JSONObject mJObj = new JSONObject(response);
JSONObject actionJsonObject = mJObj.getJSONObject("action");
String generic_message = actionJsonObject.getString("generic_message");
JSONObject domainsJsonObject = mJObj.getJSONObject("domains");
String key_example_one = domainsJsonObject.getString("key_example_one");
String api_root_url = domainsJsonObject.getString("api_root_url");
String page = mJObj.getString("page");
} catch (JSONException e) {
e.printStackTrace();
}
Check out Gson.
JsonObject jsonObject = new JsonParser().parse(jsonString).getAsJsonObject();
EDIT:
Just saw that you can't move to other Json processors. The property 'action' holds a JSONObject not a JSONArray. What about JSONObject jsonObject = mJObj.getJSONObject("action").
I am trying to get the user details using people.get in which I have emails which I need to get that value.
This is what I mean:
This is how I'm trying to do but unable to get the value
try {
String resp =profile.getEmails().toString();
JSONObject mainObject = new JSONObject(resp);
JSONObject uniObject = mainObject.getJSONObject("emails");
String email = uniObject.getString("value");
((TextView) findViewById(R.id.txtemail)).setText(email);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Any help is appreciated.
In your JSON response, emails is a JSONArray, not a JSONObject. You would need to get it like this:
JSONObject json= new JSONObject(responseString); //your response
try {
JSONArray responseArray = jsonObj.getJSONArray("email");
for (int i = 0; i < responseArray.length(); i++) {
// get value with the NODE key
JSONObject obj = responseArray.getJSONObject(i);
String lastName = obj.getString("value");
String firstName = obj.getString("type");
EmailResponse myResp = new EmailResponse();
myResp.setValue(value);
myResp.setType(type);
//set all other Strings
//lastly add this object to ArrayList<MyResponse> So you can access all data after saving
}
}
catch (JSONException e) {
e.printStackTrace();
}
POJO Class:
public class EmailResponse{
public String value = "";
public String type = "";
//getter setters
}
Hope this helps.
i have this json:
[{"id":"1","name":"john"},{"id":"2","name":"jack"},{"id":"3","name":"terry"}]
how i can parse this? i have to use a loop for extracting each group? for simple jsons i use this code:
public static String parseJSONResponse(String jsonResponse) {
try {
JSONObject json = new JSONObject(jsonResponse);
// get name & id here
String name = json.getString("name");
String id = json.getString("id");
} catch (JSONException e) {
e.printStackTrace();
}
return name;
}
but now i have to parse my new json. please help me
It should be like this:
public static String parseJSONResponse(String jsonResponse) {
try {
JSONArray jsonArray = new JSONArray(jsonResponse);
for (int index = 0; index < jsonArray.length(); index++) {
JSONObject json = jsonArray.getJSONObject(index);
// get name & id here
String name = json.getString("name");
String id = json.getString("id");
}
} catch (JSONException e) {
e.printStackTrace();
}
return name;
}
Of course you should return an array of names or whatever you want..
This is meant to be parsed by a JSONArray, and then each "record" is a JSONObject.
You can loop on the array and then retrieve the JSON String of each record with the getString(int) method. Then use this string to build a JSONObject, and just extract values like you do now.
You can use the following code:
public static void parseJSONResponse(String jsonResponse) {
try {
JSONArray jsonArray = new JSONArray(jsonResponse);
if(jsonArray != null){
for(int i=0; i<jsonArray.length(); i++){
JSONObject json = jsonArray.getJSONObject(i);
String name = json.getString("name");
String id = json.getString("id");
//Store strings data or use it
}
}
}catch (JSONException e) {
e.printStackTrace();
}
}
You need to modify the loop to store or use the data.
Hope it helps.