android how to parse json - android

public void HelloWord {
for (int i = 0; i < 20; i++) {
Log.d("Great");
}
}
The code above doesn't work why?
I try to get value name
Does anybody know where is the problem?
org.json.JSONException: Value ...Content of link... at
org.json.JSON.typeMismatch at org.json.JSONArray.

I prefer to use the GSON library, as it is a fast and effective JSON parser. Once added to the project you will need to create classes to represent the data returned. You then can call a single function to create your objects for you:
gson.fromJson();
An exceptionally good article on the use of GSON can be found at http://www.javacodegeeks.com/2011/01/android-json-parsing-gson-tutorial.html - it even uses Twitter for the example.

I think that you are missing the way that JSON works. Anything in {} is an Object, while [] designates an array. So the root of the twitter feed is a JSONObject, NOT a JSONArray:
Try something more like this:
JSONObject obj = new JSONObject(mStringBuilder.toString());
JSONObject trends = obj.getJSONObject("trends");
JSONArray today = trends.getJSONArray("2012-04-10");
for (int i = 0; i < today.length(); i++) {
JSONObject tag = today.getJSONObject(i);
String name = tag.getString("name");
// do whatever with name
}
Much easier, and its clearer how it works. JSONObjects are dictionaries, with a simple mapping between keys and values - each Object ({}) can contain either more objects, or arrays ([]) which can contain either simple integers or more objects

Related

Json - how to parse a url in Android

I want to parse json from a url and use the json data with a listview.
I also want to only list the score and the name, but I have no idea how. Thanks.
{
"level":[
{
"id":1,
"server":[
{"score":33,"name":"Car"},
{"score":72,"name":"Bus"},
]
}
]
}
Do you know how to retrieve the data?
After you retrieve the data, parsing it is very simple. To get each individual item with its attributes I would use the following code:
String responseFromUrl;
JSONObject JSONResponse = new JSONObject(responseFromURL);
JSONArray level = JSONResponse.getJSONArray("level");
//The following loop goes through each object in "level". This is nessecary if there are multiple objects in "level".
for(int i=0; i<level.length(); i++){
JSONObject object = level.get(i);
int id = object.getInteger("id");
JSONArray server = object.getJSONArray("server");
//This second loop gets the score and name for each object in "server"
for(int j=0; j<server.length(); j++){
JSONObject serverObject = server.get(i);
int score = serverObject.getInteger("score");
String name = serverObject.getString("name");
}
}
Obviously replace "responseFromUrl" with the JSON response from the url in string format. If you don't know why I used JSONObject, JSONArray, String, Integer, etc., or are just confused about this, Udacity has a good course for making http connections and parsing JSON responses from APIs.
Link to Udacity Course
You can use the gson library to convert json to an java object
Download the latest jar and import into your project, currently you can download the latest at this link:
https://repo1.maven.org/maven2/com/google/code/gson/gson/2.8.1/gson-2.8.1.jar
After, this will help you:
https://stackoverflow.com/a/23071080/4508758
Hugs!

Iterate through Java jsonObjects without array included

My problem is that this will create 3 new instances of DailyJobObjects with the same values as object number one (01, Bill, 50). And it's logical that it would do so, so how can I iterate through my jsonObject so I can separate the three objects? I have looked this up tirelessly but everything thing I have seen has and array included in the jsonData which would make things easier but this response Body is coming straight from a database - no arrays, just back to back objects. Iterating only gives me keys which I already did in a separate method to give me one half of my map. Now I need the values. You don't have to give me an answer, you can (I rather) point to something I'm missing. Thanks!
{"id":"01","name":"Bill","salary":"50"},
{"id":"02","name":"James","salary":"60"},
{"id":"03","name":"Ethan","salary":"70"}
JSONObject fields = new JSONObject(jsonData);
mObjectArray = new DailyJobObjectArray[fields.length()];
for(int i=0; i< fields.length(); i++) {
DailyJobObject mObject = new DailyJobObject();
mObject.setName(fields.getString("name"));
mObject.setSalary(fields.getString("salary"));
mObjectArray[i] = mObject;
}
return mObjectArray;
As #Selvin has mentioned, your json is not valid. Either get proper json from the database or parse it in a non-standard way. I would suggest getting a proper json array from the DB.
String[] splitString = jsondata.split("[^a-zA-Z \\{\\}]+(?![^\\{]*\\})");
for ( String s : splitString) {
try {
JSONObject field = new JSONObject(s);
String name = field.getString("name");
String id = field.getString("id");
} catch (JSONException e) {
e.printStackTrace();
}
}
I also agree that your mObject(...) does not make sense at all
Maybe you're looking for something like this
mObject.setName(name)

Wrong arrangement of data from 'for loop'

I have the following code. I added my text fields dynamically. My desired result shown in Genymotion 5.0 (Google Nexus 5) but when I run my app in other devices/actual device the textfields get shuffled. Please help, Thanks in advance.
JSONObject jsonObject = new JSONObject(question.getSublabels());
final EditText[] editTextSublabels = new EditText[jsonObject.length()];
for (int i = 0; i < jsonObject.length(); i++) {
String names = jsonObject.names().get(i).toString();
editTextSublabels[i] = (EditText) LayoutInflater.from(activity).inflate(R.layout.sublabels, null);
editTextSublabels[i].setId(i);
editTextSublabels[i].setHint(jsonObject.getString(names));
sublabelsContainers.addView(editTextSublabels[i], params);
}
You cannot and should not rely on the ordering of elements within a JSON object.
In JSON, an object is defined thus:
An object is an unordered set of name/value pairs.
If you want order to be preserved, you need to redefine your data structure or put it inside a jsonarray
see http://www.json.org.
A JSONObject is a type of map. It does not preserve ordering. If you want to preserve ordering using JSON, you will need to use an array (and matching JSONArray in Java).

Android how to change value of a Key/Value Pair inside JSONObject

Hi i want to change/alter value of a string inside a json object which inside a JSONArray and which is from a file stored in internal storage.
My initial thoughts are to convert the object to a string do a find a replace and convert back to JSONObject search the JSONArray for the JSONObject remove the old one and put the new one in. Then save the array as a .JSON File to internal storage (will this replace the file thats already there or will it create another file with the same name?).
This is my initial thoughts on how to do this but is this the correct way or is there easier more efficient way to do this?
First, you need to retrieve the required JSON Object form the JSON Array.
You can update the key-value pair of your JSON Object directly by using
mJsonObj.put("<key>", <value>).
try using this :
nameValuePairs.add(new BasicNameValuePair("cus_id", cus_id));
getting data in this:
JSONObject json = new JSONObject(responseString);
JSONArray jArray = json.getJSONArray("customer");
for (int i = 0; i < jArray.length(); i++) {
JSONObject json_data = jArray.getJSONObject(i);
cus_points = json_data.getString("cus_points");
Depends on the library you are using for parsing JSON. Some do allow code like jsonOArray.get("jsonObject").put("key", "val");
Some require to obtain the object first then do something like
JsonObj = jsonArray.get("jsonObject"); jsonObj.putVal("key", "val");
Which library do you use for processing json?

Convert from JSONArray to ArrayList<CustomObject> - Android

I converted an ArrayList to an JSONArray. How can I convert it back?
The final result must be an ArrayList. Thank you in advance.
EDIT:
This is how I convert the ArrayList to JSONArray:
String string_object= new Gson().toJson(MyArrayList<OBJECT>);
JSONArray myjsonarray = new JSONArray(string_object);
You can convert your JsonArray or json string to ArrayList<OBJECT> using Gson library as below
ArrayList<OBJECT> yourArray = new Gson().fromJson(jsonString, new TypeToken<List<OBJECT>>(){}.getType());
//or
ArrayList<OBJECT> yourArray = new Gson().fromJson(myjsonarray.toString(), new TypeToken<List<OBJECT>>(){}.getType());
Also while converting your ArrayList<OBJECT> to JsonArray, no need to convert it to string and back to JsonArray
JsonArray myjsonarray = new Gson().toJsonTree(MyArrayList<OBJECT>).getAsJsonArray();
Refer Gson API documentation for more details. Hope this will be helpful.
JSONArray is just a subclass of object, so if you want to get the JSONObjects out of a JSONArray into some other form, JSONArray doesn't have any convenient way to do it, so you have to get each JSONObject and populate your ArrayList yourself.
Here is a simple way to do it:
ArrayList<JSONObject> arrayList = new ArrayList(myJSONArray.length());
for(int i=0;i < myJSONArray.length();i++){
arrayList.add(myJSONArray.getJSONObject(i));
}
EDIT:
OK, you edited your code to show that you are using GSON. That is a horse of a different color. If you use com.google.gson.JsonArray instead of JSONArray, you can use the Gson.fromJson() method to get an ArrayList.
Here is a link: Gson - convert from Json to a typed ArrayList
Unfortunately, this will require a little work on your part. Gson does not support deserializing generic collections of arbitrary objects. The Gson User Guide topic Serializing and Deserializing Collection with Objects of Arbitrary Types list three options for doing what you want. To quote the relevant parts of the guide:
You can serialize the collection with Gson without doing anything specific: toJson(collection) would write out the desired output.
However, deserialization with fromJson(json, Collection.class) will not work since Gson has no way of knowing how to map the input to the types. Gson requires that you provide a genericised version of collection type in fromJson. So, you have three options:
Option 1: Use Gson's parser API (low-level streaming parser or the DOM parser JsonParser) to parse the array elements and then use Gson.fromJson() on each of the array elements. This is the preferred approach. Here is an example that demonstrates how to do this.
Option 2: Register a type adapter for Collection.class that looks at each of the array members and maps them to appropriate objects. The disadvantage of this approach is that it will screw up deserialization of other collection types in Gson.
Option 3: Register a type adapter for MyCollectionMemberType and use fromJson with Collection<MyCollectionMemberType>
This approach is practical only if the array appears as a top-level element or if you can change the field type holding the collection to be of type Collection<MyCollectionMemberType>.
See the docs for details on each of the three options.
we starting from conversion [ JSONArray -> List < JSONObject > ]
public static List<JSONObject> getJSONObjectListFromJSONArray(JSONArray array)
throws JSONException {
ArrayList<JSONObject> jsonObjects = new ArrayList<>();
for (int i = 0;
i < (array != null ? array.length() : 0);
jsonObjects.add(array.getJSONObject(i++))
);
return jsonObjects;
}
next create generic version replacing array.getJSONObject(i++) with POJO
example :
public <T> static List<T> getJSONObjectListFromJSONArray(Class<T> forClass, JSONArray array)
throws JSONException {
ArrayList<Tt> tObjects = new ArrayList<>();
for (int i = 0;
i < (array != null ? array.length() : 0);
tObjects.add( (T) createT(forClass, array.getJSONObject(i++)))
);
return tObjects;
}
private static T createT(Class<T> forCLass, JSONObject jObject) {
// instantiate via reflection / use constructor or whatsoever
T tObject = forClass.newInstance();
// if not using constuctor args fill up
//
// return new pojo filled object
return tObject;
}
Try this,
ArrayList<**YOUCLASS**> **YOURARRAY** =
new Gson().fromJson(oldJSONArray.toString(),
new TypeToken<List<**yourClass**>>(){}.getType());

Categories

Resources