How to combine to json arrays - android

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

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

how can I collect the array heroes in my android studio project below

my function is
public String[] loadIntoListView(String json) throws JSONException {
JSONArray jsonArray = new JSONArray(json);
String[] heroes = new String[3];
for (int i = 0; i < 3; i++)
{
JSONObject obj = jsonArray.getJSONObject(i);
// heroes[i] = obj.getString("name");
heroes[i]= "https://static.pexels.com/photos/1543/landscape-nature-man-person-medium.jpg";
}
return heroes;
}
this is where i called it but it is returning null array for me
String s="";
try {
items= loadIntoListView(s);
} catch (JSONException e) {
e.printStackTrace();
}
The line JSONArray jsonArray = new JSONArray(json); may be crashing due to json not being a valid json array. This would cause the array to be null, as it hasn't been initialized yet.
Your exception handler out of for. If you catch exceptions in for body, you can parse verified json items. If a item not correct, you can pass.
For example,
public String[] loadIntoListView(String json) {
JSONArray jsonArray = new JSONArray(json);
ArrayList<String> heroes = new ArrayList();
for (int i = 0; i < jsonArray.length; i++)
{
try{
JSONObject obj = jsonArray.getJSONObject(i);
heroes.add(obj.getString("name"));
}catch(JSONException ignore_errors){
}
}
return heroes.toArray(new String[0]);;
}

Regd : getting value from json url

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

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

How stop a for loop when parsing a JSONArray for nameless JSONObject?

I want to parse a JSONArray that contains JSONObjects that have no names and whose (index int) positions within the array changes every week or so. I have attempted to parse a particular Object by it's attributes, but my parser only returns the last Object in the array.
How can i stop my loop when it reaches the object i want to parse and determine the int index of the object for further parsing.
try {
JSONArray jArray = JSONthing.getJSONfromURL("http://something.com");
String attributeiwant = "abc";
for (int i = 0; i < jArray.length(); i++) {
JSONObject alpha = jArray.getJSONObject(i);
String attributeparsed = alpha.getString("widget");
if (attributeparsed == attributeiwant) {
//determine int index of object, so i can parse other attributes
//from same object
}
}
} catch (Exception e) {
Log.e("log_tag", "Error parsing data "+ e.toString());
}
use String.equals for comparing Strings instead of ==
try {
JSONArray jArray = JSONthing.getJSONfromURL("http://something.com");
String attributeiwant = "abc";
for (int i = 0; i < jArray.length(); i++) {
JSONObject alpha = jArray.getJSONObject(i);
String attributeparsed = alpha.getString("widget");
if (attributeparsed.equals(attributeiwant)) {
//determine int index of object, so i can parse other attributes
//from same object
// Get data from JsonObject
break;
}
}
} catch (Exception e) {
Log.e("log_tag", "Error parsing data "+ e.toString());
}
use break; statement to break the loop, change your code to following:
int i = 0;
try {
JSONArray jArray = JSONthing.getJSONfromURL("http://something.com");
String attributeiwant = "abc";
for (; i < jArray.length(); i++) {
JSONObject alpha = jArray.getJSONObject(i);
String attributeparsed = alpha.getString("widget");
if (attributeparsed.equals(attributeiwant)) {
//determine int index of object, so i can parse other attributes
//from same object
break;
}
}
} catch (Exception e) {
Log.e("log_tag", "Error parsing data "+ e.toString());
}
if(i<jArray.length())
{
//item found, use i as index of object.
}
else
//item not found.

Categories

Resources