Regd : getting value from json url - android

I want to get the id ^& content value in http://rest-service.guides.spring.io/greeting
What i tried is,
try {
JSONObject jsonObj = new JSONObject(parsingUrl);
// If you have array
JSONArray resultArray = jsonObj.getJSONArray("id"); // Here you will get the Array
// Iterate the loop
for (int i = 0; i < resultArray.length(); i++) {
// get value with the NODE key
JSONObject obj = resultArray.getJSONObject(i);
String name = obj.getString("content");
}
// If you have object
//String result1 = jsonObj.getString("result");
} catch (Exception e) {
e.printStackTrace();
}
Thanks

The url that your mentioned dont have json arrays, parsing will be like
try {
JSONObject jsonObj = new JSONObject(resultfromUrl);
int id = jsonObj.getInt("id");
String name = jsonObj.getString("content");
} catch (JSONException e) {
e.printStackTrace();
}

Related

How to parse a JSONArray and assign it to different TextViews?

I have a JSONArray and when I try to parse it, an NPE shows and the logcat shows W/System.err: org.json.JSONException: Value at 0 is null. Please help. I have provided my codes below.
JSON Array
[
{
"student_number":"201411870",
"full_name":"Miranda , Andrew Matthew Matera",
"year":"4",
"course":"BSIT"
}
]
Code Snippet
ArrayList<User> userArrayList = new JsonConverter<User>().toArrayList(response, User.class);
JSONArray jsonArray = new JSONArray(userArrayList);
try {
int regStudentNumber = jsonArray.getJSONObject(0).getInt("student_number");
String regFullName = jsonArray.getJSONObject(1).getString("full_name");
int regYear = jsonArray.getJSONObject(2).getInt("year");
String regCourse = jsonArray.getJSONObject(3).getString("course");
tvStudentNumber.setText(String.valueOf(regStudentNumber));
tvFullName.setText(regFullName);
tvYear.setText(String.valueOf(regYear));
tvCourse.setText(regCourse);
} catch (JSONException e) {
e.printStackTrace();
}
Solved it on my own. Sorry for the unclear question.
try {
JSONArray jsonArray = new JSONArray(response);
if(jsonArray != null) {
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
int regStudentNumber = jsonObject.getInt("student_number");
String regFullName = jsonObject.getString("full_name");
int regYear = jsonObject.getInt("year");
String regCourse = jsonObject.getString("course");
tvStudentNumber.setText(String.valueOf(regStudentNumber));
tvFullName.setText(regFullName);
tvYear.setText(String.valueOf(regYear));
tvCourse.setText(regCourse);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
First of all parse JSON array to object to make clear it is for a particular value then fetch things from it based on need.
To parse json array to object use code
try {
JSONArray jsonArray = new JSONArray(response);
if(jsonArray != null) {
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
}
}
} catch (JSONException e) {
e.printStackTrace();
}

Json move to next item

I have a dynamic JSON string that looks like this:
{"_id":"7","food_name":"Fiber Balance"},{"_id":"8","food_name":"Sport +"}
I am able to get the first name, but not the second one. This is my code for getting the first (Fiber Balance):
// Dynamic text
TextView textViewDynamicText = (TextView)getActivity().findViewById(R.id.textViewDynamicText);
String stringJSON = textViewDynamicText.getText().toString();
String stringFoodname = "";
try {
JSONObject jsonObject = new JSONObject(stringJSON);
Iterator<String> iter = jsonObject.keys();
while (iter.hasNext()) {
String key = iter.next();
try {
stringFoodname = jsonObject.getString("food_name");
Toast.makeText(getContext(), stringFoodname, Toast.LENGTH_LONG).show();
} catch (JSONException e) {
// Something went wrong!
}
}
} catch (org.json.JSONException e) {
// Something went wrong!
}
How can I go to the next item in the json string?
If you have multiple data than you need to use Array,if you want to get all data from your json use below trick,
String json = "{\"_id\":\"7\",\"food_name\":\"Fiber Balance\"},{\"_id\":\"8\",\"food_name\":\"Sport +\"}";
json = "[" + json + "]";
try {
JSONArray array = new JSONArray(json);
for (int i = 0; i < array.length(); i++) {
JSONObject object = array.getJSONObject(i);
String foodName = object.getString("food_name");
Log.e("FoodName:", foodName);
}
} catch (JSONException e) {
e.printStackTrace();
Log.e("error", "json", e);
}

How to combine to json arrays

In order to combine 2 JSON arrays into one I use the following code (the input data areJSON arrays that wereconverted to a string)
private static String combineData(String Data, String data){
if (empty(data))
data = Data;
else { // need to append the data
try {
// first, convert the strings back to JSON objects
JSONObject jsonObj1 = new JSONObject(data); // existing data
JSONObject jsonObj2 = new JSONObject(Data); // new data
// Getting Array of Providers
String fieldName = context.getString(R.string.JSON_COMP_RECORDS);
// Second, get the array out of the JSON object
JSONArray record1 = jsonObj1.getJSONArray(fieldName);
JSONArray record2 = jsonObj2.getJSONArray(fieldName);
// Third, join them into one array
JSONArray arr = new JSONArray();
// LOOP 1 - get individual JSON objects
for (int i = 0; i < record1.length(); i++) {
JSONObject c;
try {
c = record1.getJSONObject(i);
} catch (JSONException e) {
e.printStackTrace();
return data;
}
arr.put (c);
}
// LOOP 1 - get individual JSON objects
for (int i = 0; i < record2.length(); i++) {
JSONObject c;
try {
c = record2.getJSONObject(i);
} catch (JSONException e) {
e.printStackTrace();
return data;
}
arr.put (c);
}
JSONObject json = new JSONObject();
json.put (context.getString(R.string.JSON_COMP_RECORDS), arr);
data = json.toString();
} catch (JSONException e) {
e.printStackTrace();
}
}
return data;
}
I wonder if there is a way to do it more efficiently and get rid of the 2 loops?
How about this ? You can put JSONObject directly int another array
JSONArray record1 = jsonObj1.getJSONArray(fieldName);
JSONArray record2 = jsonObj2.getJSONArray(fieldName);
for (int i = 0; i < record1.length(); i++) {
JSONObject c;
try {
c = record1.getJSONObject(i);
} catch (JSONException e) {
e.printStackTrace();
return data;
}
record2.put (c);
}
Hope this helps
JSONArray record1 = jsonObj1.getJSONArray(fieldName);
JSONArray record2 = jsonObj2.getJSONArray(fieldName);
for (int i = 0; i < record1.length(); i++) {
record2.put(record1.getJSONObject(i));
}

Covnert JSON to string in android

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.

could not be able to get data from json webservice

I want to get data from a jason webservice,
JSON response is :
{"content":[{"id":"1","asset_id":"62","title":"sample page","alias":"","introtext":"","fulltext":"Some Contents"},{"id":"2","asset_id":"62","title":"sample page2","alias":"","introtext":"","fulltext":"Some Contents"},{"id":"3","asset_id":"62","title":"sample page3","alias":"","introtext":"","fulltext":"Some Contents"}]}
After Visiting Here
I have done in this way:
private void parseData() {
// Creating JSON Parser instance
JSONParser jParser = new JSONParser();
// getting JSON string from URL
JSONObject json = jParser.getJSONFromUrl(BASE_URL);
try {
// Getting Array of Contents
contents = json.getJSONArray(TAG_CONTENTS);
// looping through All Contents
for(int i = 0; i < contents.length(); i++){
JSONObject c = contents.getJSONObject(i);
// Storing each json item in variable
id = c.getString(TAG_ID);
title = c.getString(TAG_TITLE);
}
textView.setText(id + " " + title);
} catch (JSONException e) {
e.printStackTrace();
}
}
Now I got id = 3 and title = sample page3result now how can I get first two values as also!!?
Arshay!! Try This One Man!!
private void parseData() {
// Creating JSON Parser instance
MyJSONParser jParser = new MyJSONParser();
// getting JSON string from URL
JSONObject json = jParser.getJSONFromUrl(BASE_URL);
try {
// Getting Array of Contents
jsonArrar = json.getJSONArray(TAG_CONTENTS);
List list = new ArrayList<String>();
// looping through All Contents
for(int i = 0; i < jsonArrar.length(); i++){
// JSONObject c = jsonArrar.getJSONObject(i);
String id1=jsonArrar.getJSONObject(i).getString(TAG_ID);
String title=jsonArrar.getJSONObject(i).getString(TAG_TITLE);
String fullText=jsonArrar.getJSONObject(i).getString(TAG_FULL_TEXT);
list.add(id1);
list.add(title);
list.add(fullText);
}
Iterator<String> iterator = list.iterator();
StringBuilder builder = new StringBuilder();
while (iterator.hasNext()) {
String string = iterator.next();
builder.append(string+"\n");
}
textView.setText(builder);
} catch (JSONException e) {
e.printStackTrace();
}
}
Your line is JSONObject and not JSONArray.
You should use it like that:
JSONObject jso = new JSONObject(line);
JSONArray jsa = new JSONArray(jso.getJSONArray("content"));
Try something like this
// jsonData : response
List< String> contents = new ArrayList< String>();
String[] val;
try {
JSONObject jsonObj = new JSONObject(jsonData);
if (jsonObj.get(JSON_ROOT_KEY) instanceof JSONArray) {
JSONArray array = jsonObj.optJSONArray(JSON_ROOT_KEY);
for (int loop = 0; loop < array.length(); loop++) {
val = new String[loop];
JSONObject Jsonval = array.getJSONObject(loop);
val.Jsonval.getString(TAG_ID);
val.Jsonval.getString(asset_id);
.
.
etc
contents.add(val);
}
}
}

Categories

Resources