Android json array: how do I get and specific string? [duplicate] - android

This question already has answers here:
How do I parse JSON in Android? [duplicate]
(3 answers)
Closed 6 years ago.
I have a Json script which get data from a Mysql database and print it in different TextViews. The thing I want to know is how can I take for example only the "idE" value and print it in the "TextViewTitulo" TextView
try {
String response = "[{"0":"1","id":"1","1":"f3n","idE":"f3n","2":"bar","tipo":"bar"},{"0":"1","id":"1","1":"f3n","idE":"f3n","2":"bar2","tipo":"bar2"}]"
JSONArray array;
array = new JSONArray(response);
StringBuilder sb = new StringBuilder();
for (i=0; i<array.length(); i++) {
// chain each string, separated with a new line
sb.append(array.getString(i) + "\n");
}
// display the content on textview
textViewTitulo.setText(sb.toString());
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
My code works fine, but is displays the whole string of values

You have 2 objects in your JSONArray, and 1 textview to show the data in, so I'm adding append " " to separate them.
for (i=0; i<array.length(); i++) {
sb.append(array.getJSONObject(i).getString("idE"));
sb.append(" ");
//do whatever with it
}
textViewTitulo.setText(sb.toString());

Of course you can get it, you just have to iterate through the whole JSONArray. If you know the value you are looking for, you have to search for it, if you know the index - it is easier, you just have to get it. So for the first case, you could do something like:
for (int i = 0; i < array.length(); i++) {
JSONObject current = array.getJSONObject(i);
// In your case the JSONObject is more complicated
// so you need to iterate over it too
Iterator<?> keys = current.keys();
while(keys.hasNext()) {
String key = (String)keys.next();
String value = current.get(key);
// Do something with the value
}
// Or If you know what key you are looking for, you may do
String value = current.get("idE");
// Do something with value
}

Related

get JSONArray data inside JSONArray

I need to get "examples" data that is an array inside of 'results'
JSON FILE
and append it to a string. What would be the easiest way to do that?
this is how i would get "definitions"
private JSONObject queryResults;
...
...
String finalResults = "";
JSONArray results = queryResults.getJSONArray("results");
for(int i = 0; i < results.length(); i++){
JSONObject item = results.getJSONObject(i);
finalResults += item.getString("definition") + " ";
}
As this topic is related to Android application, the easiest way to get the mentioned value without using any additional libraries is to check if JSONObject inside the for-loop has attribute definitions and get the value as a String.
You can go with it like this
String finalExamples = "";
JSONArray results = queryResults.getJSONArray("results");
for (int i=0; i < results.length(), i++) {
JSONObject item = results.getJSONObject(i);
if (item.has("examples")) {
examples += item.getString("examples");
}
}
I assumed that you don't want to update your result String value if examples is not available in the JSONObject.
If you want to handle other cases, for example when "examples" is available in the object but is null or is set to empty String you can use other methods of JSONObject to check it.
More info about working with JSONObjects you can find in the documentation

How can i parse this json file in android studio? [duplicate]

This question already has answers here:
Android Parse JSON Array
(3 answers)
Closed 6 years ago.
how can i parse this json file because the text do not have any particular indexing names
{
"titles": [
" Thoughts On The Works Of Providence",
"\"All Is Vanity, Saith the Preacher\"",
"\"And the sins of the fathers shall be\"",
"\"Arcturus\" is his other name",
"\"By the Waters of Babylon.\"",
"\"De Gustibus--\"",
"\"Faith\" is a fine invention",
"\"Faithful to the end\" Amended",
"\"Heaven\" -- is what I cannot reach!",
"\"Heaven\" has different Signs -- to me --",
"\"Heavenly Father\" -- take to thee",
"\"Home\"",
]
}
Like this:
JSONArray array = object.getJSONArray("titles");
for(int i = 0; i < array.length(); i ++){
String title = array.getString(i);
//Do something with the string
}
You treat the JsonArray like a string array.
However in the array you provided the JSON is invalid because of the comma on the last element of the array, you need to remove this comma to have valid JSON.
It's just a simple JSON. Do it like this.
String json = "{\"titles\":[\" Thoughts On The Works Of Providence\",\"\\\"All Is Vanity, Saith the Preacher\\\"\",\"\\\"And the sins of the fathers shall be\\\"\",\"\\\"Arcturus\\\" is his other name\",\"\\\"By the Waters of Babylon.\\\"\",\"\\\"De Gustibus--\\\"\",\"\\\"Faith\\\" is a fine invention\",\"\\\"Faithful to the end\\\" Amended\",\"\\\"Heaven\\\" -- is what I cannot reach!\",\"\\\"Heaven\\\" has different Signs -- to me --\",\"\\\"Heavenly Father\\\" -- take to thee\",\"\\\"Home\\\"\"]}";
JSONObject jsonObject = new JSONObject(json);
And for accessing your items:
JSONArray jsonArray = jsonObject.getJSONArray("titles");
for(int i=0;i<jsonArray.size(); i++){
Log.d(TAG, jsonArray.getString(i));
}
You can parse this to an instanse of this class :
public class Instance{
public String[] titles;
}
but you need to remove the last comma after home. If there is no another item after the comma, it means it is not a valid JSON string.
This should work.
JSONObject jsonObject = new JSONObject(yourString);
JSONArray jsonArray= jsonObject.getJSONArray("titles");
for (int i=0; i < jsonArray.length(); i++) {
string content = jsonArray.getString(i);
....
}
Try this:
Try{
JSONArray itemArray = jsonObject.getJSONArray("titles")
for (int i = 0; i < itemArray.length(); i++) {
String value=itemArray.getString(i);
Log.e("json", i+"="+value);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

How to get array number JSON android

I have JSON :
{"elements":[{"id":5,"name":"Mathematics","shortName":"math","links":{"courses":[15,30,46,47]}}]}
My code :
List<NameValuePair> params = new ArrayList<NameValuePair>();
// getting JSON string from URL
JSONObject json = jParser.makeHttpRequest(url_all_products, "GET", params);
// Check your log cat for JSON reponse
//Log.d("All Products: ", json.toString());
try {
products = json.getJSONArray("elements");
for (int i = 0; i < products.length(); i++) {
JSONObject c = products.getJSONObject(i);
// Storing each json item in variable
int ids = c.getInt(TAG_PID);
String id = String.valueOf(ids);
if (id.compareTo(id_kh) == 0) {
object = c.getJSONObject("links");
JSONArray courses = object.getJSONArray("courses");///???????????
//result = courses.split("[,]");
Toast.makeText(getBaseContext(),"abc",Toast.LENGTH_LONG).show();
break;
}
}
} catch (JSONException e) {
e.printStackTrace();
}
I dont know to get array number after "courses".
I would use HashMaps. Here you have an example (creating Hashmap from a JSON String
) how to get it from a JSON String.
Particularly for the "courses", once you have been parsed until there, I would use a HashMap<String,List<Integer>>
courses is a JSONArray, so you can do like that:
JSONArray coursesArray = linksObject.getJSONArray("courses");
UPDATE:
To get values from coursesArray :
int value = coursesArray.optInt(position);
Almost there. Once you get your
JSONArray courses = object.getJSONArray("courses");
simply iterate over its values:
// you wanted these numbers in an array
// so let's create one, with size being number of elements in
// JSONArray courses
int[] courseIds = new int[courses.length()];
for (int j=0; j<courses.length(); j++) {
// assign current number to the appropriate element in your array of ints
coursesId[j] = courses.getInt(j);
Log.d("TAG", "number: " + number);
}
The above will save these numbers in an array and print them too:
number: 15
number: 30
number: 46
number: 47
Just keep in mind that "courses" key might not exist, the array might be empty etc.

Android get string from an Array and create another array

Hi im creating a list that has headers of dates and then content underneath. i have a JSON feed that contains fixtures inside each is an array containing the data for each fixture one string i need is matchdate to create my headers however if i was to just run through it it will create multiple instances of the same match day so id have 3 headers with the same date for example. how can i extract that information and the create another array that says if this date already exists go through the next one and so on. i know it's pretty specific question but if someone could at least point me in the right direction. thanks in advance.
heres my feed
fixturesArray = [{"awayteam":"Team 1","comp":"LGE","location":null,"attendance":null,"awayscore":null,"division":"Testing 1","homescore":null,"fixture_note":null,"kickoff":"15:30:00","awayteam_id":"64930","matchdate":"2012-07-07","awaypens":null,"homepens":null,"division_id":"5059","hometeam":"Team 3","hometeam_id":"64932"},{"awayteam":"Team 2","comp":"LGE","location":null,"attendance":null,"awayscore":null,"division":"Testing 1","homescore":null,"fixture_note":null,"kickoff":"15:00:00","awayteam_id":"64931","matchdate":"2012-07-07","awaypens":null,"homepens":null,"division_id":"5059","hometeam":"Team 4","hometeam_id":"64933"},{"awayteam":"Team 4","comp":"LGE","location":null,"attendance":null,"awayscore":null,"division":"Testing 1","homescore":null,"fixture_note":null,"kickoff":"15:00:00","awayteam_id":"64933","matchdate":"2012-07-14","awaypens":null,"homepens":null,"division_id":"5059","hometeam":"Team 1","hometeam_id":"64930"}]
heres what i have tried so far
Log.v("MyFix", "fixturesArray = " + fixturesArray);
if(fixturesArray.length() < 1){
TextView emptytext = (TextView) fixturesView.findViewById(R.id.TextView02);
emptytext.setText("No Upcoming Fixtures Available");
}else{
try{
JSONArray datesArray = null;
fixturesInfo = null;
String matchDateTemp = "";
for(int t = 0; t < fixturesArray.length(); t++){
JSONObject matchDateDict = fixturesArray.getJSONObject(t);
String matchDate = matchDateDict.getString("matchdate");
JSONArray matchdates = matchdates.put(matchDate);
Log.v("MyFix", "matchdate = " + matchDate);
tempArray.put(t, fixturesArray);
fixturesInfo.put(matchDate, tempArray);
}
Log.v("MyFix", "fixturesInfo = " + fixturesInfo);
Log.v("MyFix", "tempArray = " + tempArray);
}catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Just get the piece of data then iterate through the new arraylist checking for a duplicate before adding.
int matchCount=0; // set count of matches to 0
String matchDate = matchDateDict.getString("matchdate"); // get the data to compare
for (int i = 0; i < uniqueDateArrayList.size(); i++){ // set loop to iterate through unique date arraylist
if (matchDate.equals(uniqueDateArray[i])){ // compare the date to the date stored at position i
matchCount++; // if it matches increase the match count
}
}
if (matchCount == 0) {
uniqueDateArrayList.add(matchDate) // if there is no matching date, add it to the unique date arraylist
}
That should give you an array list containing all of the unique dates in your data.

JSON Array of strings (no objects), extracting data

I have a long JSON string representing a string[] array being returned from a WCF service. The array elements are simply strings, they are not objects. This is an example of the return data
["1|ArrayElement1","2|ArrayElement2","3|ArrayElement3"..."n|ArrayElementn"]
I don't mind the index being included in the string, but I need to parse the strings into an ArrayList in Android so that I can adapt it to a ListView.
Since these technically aren't JSONObjects, how can I iterate over them and extract the string from each array element?
this is a valid JSON array of strings, you can parse it normally like this
JSONArray jsonStrings = json.getJSONArray("items");
String strings[] = new String[jsonStrings.length()];
for(int i=0;i<strings.length;i++) {
strings[i] = jsonStrings.getString(i);
}
Maybe this post can help you out:
JSON Array iteration in Android/Java
HashMap<String, String> applicationSettings = new HashMap<String,String>();
for(int i = 0; i < settings.length(); i++){
String value = settings.getJSONObject(i).getString("value");
String name = settings.getJSONObject(i).getString("name");
applicationSettings.put(name, value);
}
JSONArray names= json.names();
JSONArray values = json.toJSONArray(names);
for(int i = 0 ; i < values.length(); i++){
if(names.getString(i).equals("description")){
setDescription(values.getString(i));
}
else if(names.getString(i).equals("expiryDate")){
String dateString = values.getString(i);
setExpiryDate(stringToDateHelper(dateString));
}
else if(names.getString(i).equals("id")){
setId(values.getLong(i));
}
else if(names.getString(i).equals("offerCode")){
setOfferCode(values.getString(i));
}
else if(names.getString(i).equals("startDate")){
String dateString = values.getString(i);
setStartDate(stringToDateHelper(dateString));
}
else if(names.getString(i).equals("title")){
setTitle(values.getString(i));
}
}
Just to clarify, as I understand it you are receiving a JSON array of strings which are strings of valid JSON prefixed with the array index and a pipe character?
First, I would suggest contacting the creator of this abomination and lecturing them on violating standards. If they won't listen, talk to their bosses. This kind of thing is unacceptable in my opinion and needs to stop.
Second, I'd suggest doing something like this:
string[] element_strings = JSON.deserialize(WCF_string_result);
object[] elements = new object[element_strings.length];
for(int x = 0; x < elements.length; x++)
{
int pipeIndex = element_strings.indexOf("|");
elements[x] = JSON.deserialize(element_strings[x].substr(pipeIndex + 1));
}
Of course this assumes you have some kind of method for deserializing strings of JSON objects. If you don't I'd recommend using the built in library available in Android:
http://developer.android.com/reference/org/json/package-summary.html
If you want to extract specific value from it using Java8 stream on JSONArray. Then this code will help.
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import org.json.JSONArray;
public class JsonArrayTest {
public static void main(String[] args) {
System.out.println("Output - "+ getValue("[{\"id\":\"11\",\"username\":\"ABC\"},{\"id\":\"12\",\"username\":\"ABC\"}]\""));
System.out.println("Output - "+ getValue("[{\"id\":\"13\",\"username\":\"XYZ\"}]\""));
}
private static String getValue(String input) {
JSONArray jsonArray = new JSONArray(input);
return IntStream
.range(0, jsonArray.length()).mapToObj(obj -> jsonArray.getJSONObject(obj))
.filter(filterObj -> filterObj.getString("id") != null && "12".equals(filterObj.getString("id")))
.map(finalObj -> finalObj.getString("username")).collect(Collectors.joining(""));
}
}
Note: This is just an example how can you extract a specific value from JSONArry using stream APIs. You can change the filter condition or drop it according to your requirement.

Categories

Resources