Json object to json array Java (Android) - android

It's been a while and i'm trying to ignore some frustrating issue i'm having with json things in java, i'm new to this and read alot however, parsing json in javascript or php was alot better (or easier i dunno) but now in java i cannot convert a jsonobject to jsonarray if it doesn't have a parent, cuz it uses .getJsonArray('array)
BUT what IF i have this :
{"49588":"1.4 TB","49589":"1.4 TB MultiAir","49590":"1.4 TB MultiAir TCT","49591":"1.6L MultiJet","49592":"1750 Tbi","49593":"2.0L MultiJet","49594":"2.0L MultiJet TCT"}
i'm not succeeding in anyway to convert it to array
what i want is to convert this JSONObject to JSONArray loop within its items and add them to a Spinner, now that's the first issue, the second question is: if i convert this to JSONArray how can i add the ID, Text to the spinner? just like the HTML Select tag
<option value="0">Item 1</option>
so it's an issue and a question hope someone can find the solution for this jsonarray thing, without modifying the json output from the website, knowing that if i modify and add a parent to this json, the JSONArray will work. but i want to find the solution for that.
Nothing special i have in the code:
Just a AsynTask Response, a log which is showing the json output i put at the beginning of this question
Log.d("response", "res " + response);
// This will work
jsonCarsTrim = new JSONObject(response);
// This won't work
JSONArray jdata = new JSONArray(response);
Thanks !

How about this:
JSONObject json = new JSONObject(yourObject);
Iterator itr = json.keys();
ArrayList<CharSequence> entries = new ArrayList<CharSequence>();
ArrayList<Integer> links = new ArrayList<Integer>();
int i = 0;
while(itr.hasNext()) {
String key = itr.next().toString();
links.add(i,Integer.parseInt(key));
entries.add(i, (CharSequence) json.getString(key)); //for example
i++;
}
//this is the activity
entriesAdapter = new ArrayAdapter<CharSequence>(this,
R.layout.support_simple_spinner_dropdown_item, entries);
//spinner is the spinner the data is added too
spinner.setAdapter(entriesAdapter);
this should work (works for me), you may have to modify the code.
The way shown, i am adding all entries of the json object into a Spinner, where my json key is the index value and the linked String value of the json object will be shown as Spinner entry (title) in my activity.
Now when an Item is selected, fetch the SelectedItemPosition and you can look it up in the "links" array list, to get the real value.

I'm not sure if this is thing you want but give it a try. There is tutorial to convert the Json to Map. After you convert it, you can iterate through the map.
http://www.mkyong.com/java/how-to-convert-java-map-to-from-json-jackson/

What you have is a JSON object type, not an array type. To iterate you can get the Iterator from the keys method.

Related

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)

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

Android Not Sure How To Refer To Value In JSON File (JSON Parsing)

Example JSON Page
http://maps.googleapis.com/maps/api/geocode/json?latlng=51.155455,-0.165058&sensor=true
#SuppressLint("NewApi")
public void readAndParseJSON(String in) {
try {
JSONObject reader = new JSONObject(in);
// This works and returns address
JSONArray resultArry = reader.getJSONArray("results");
String Address = resultArry.getJSONObject(1).getString("formatted_address").toString();
Log.e("Address", Address);
// Trying to get PostCode on code below - this is not working (log says no value at address components)
JSONArray postCodeArray = reader.getJSONArray("address_components");
String postCode = postCodeArray.getJSONObject(1).getString("long_name").toString();
Log.e("PostCode", postCode );
This code returns the address correctly. How can I get the post code long_name which is inside address_components?
Solution
I had to get each array, and then get the post code value.
I am using the value 7, as that is the JSONObject that has the postcode stored in the "long_name" field.
JSONObject readerJsonObject = new JSONObject(in);
readerJsonObject.getJSONArray("results");
JSONArray resultsJsonArray = readerJsonObject.getJSONArray("results");
JSONArray postCodeJsonArray = resultsJsonArray.getJSONObject(0).getJSONArray("address_components");
String postCodeString = postCodeJsonArray.getJSONObject(7).getString("long_name").toString();
Log.e("TAG", postCodeString);
Hope that helps.
reader.getJSONObject(1).getJSONArray("address_components");
Your problem is that results is a JSONArray that contains a child JSONObject composed of several children: "address_components", "formatted_address", "geometry", and "types". The result array actually contains many of these such objects, but let's focus on just the first child for now.
Look carefully at your code. With this line:
JSONArray resultArry = reader.getJSONArray("results");
You are getting the entire results. Later on, you then call the same method again:
JSONArray postCodeArray = reader.getJSONArray("address_components");
But you're asking for an "address_components" from the reader, where I do not expect you'll find anything (having already read the entire result before.) You should instead be working with the JSONArray you already got before, since it already contains the entire result.
Try something like:
JSONObject addressComponents = resultArry.getJSONObject(1).getJSONObject("address_components");
String postCode = addressComponents.getString("long_name");
Note: I don't know why you're singling out JSONObject #1 (as opposed to 0, which is the first, or any other one of them) and I also am not sure why you named the String postCode. So if I've misunderstood your intention, I apologize.
Is difficult to find the error... because all looks well. The problem maybe can exist when you make the json.put("address_components", something);
So my advice is put a breakpoint at this line
JSONArray postCodeArray = reader.getJSONArray("address_components");
o display the json in logcat
Log.d("Simple", reader.toString());
Then Paste your json in this web page to view more pretty
http://jsonviewer.stack.hu/
and check if all keys are stored well.
Solution
Need to get each array, and then get the post code value. The value 7 is used, as that is the JSONObject that has the postcode stored in the "long_name" field.
JSONObject readerJsonObject = new JSONObject(in);
readerJsonObject.getJSONArray("results");
JSONArray resultsJsonArray = readerJsonObject.getJSONArray("results");
JSONArray postCodeJsonArray = resultsJsonArray.getJSONObject(0).getJSONArray("address_components");
String postCodeString = postCodeJsonArray.getJSONObject(7).getString("long_name").toString();
Log.e("TAG", postCodeString);
Hope that helps.

Get unknow number of values in Jsonobject and set them into spinner for Android

I'm doing an application that need to receive an unknow number of names with they and a id.
I have solved the php and mysql part and this is what I receive into my app:
[{"id":"3","nombre":"Kaotik Sabadel"},{"id":"4","nombre":"Promotor Kaotik"}]
In the android part I start with this:
myJsonObj = new JSONObject(jodata);
and that's all I have.
And I want to set the names (nombre) into an spinner and when the user choose this name, get the value of his id...
You need to implement a custom SpinnerAdapter which parses the JSONArray (and no JSONObject) and fills the data into your Spinner.
As a little hint how to parse the data use this code:
JSONArray data=new JSONArray(json);
for(int i=0; i<data.length(); i++) {
JSONObject element=data.getJSONObject(i);
int id=element.getInt("id");
// ...
}
The part with the id may failes because it is a string and no integer just now I don't know if JSONObject can detect that the value can be casted to an int. If not use getString and parse it to a int.

how to generate JsonStringer for this Json Data Format?

hello i have a JSON data format can anyone please help me to make dynamic JSONStringer object for this String
{"Text":"Hello Simple Text",
"Files":[{"ContentType":"image/png",
"Content":"iVBORw0KGgoAAAANSUhEUgAAAR8AAACMCAIAAADKsDpDAAAACXBIWXMAAA7EAAAOxAGVKw4bAAAAB3RJTUUH2wYWDzIB3zSYdQAAAAd0RVh0QXV0aG9yAKmuzEgAAAAMdEVYdERlc2NyaXB0aW9uABMJISMAAAAKdEVYdENvcHlyaWdodACsD8w6AAAADnRFWHRDcmVhdGlvbiB0aW1lADX3DwkAAAAJdEVYdFNvZnR3YXJlAF1w/zoAAAALdEVYdERpc2NsYWltZXIAt8C0jwAAAAh0RVh0V2FybmluZwDAG+aHAAAAB3RFWHRTb3VyY2UA9f+D6wAAAAh0RVh0Q29tbWVudAD2zJa/AAAABnRFWHRUaXRsZQCo7tInAAABAElEQVR4nO2de1zUVf7/3+dzmwsMoCgDXgARBO/"}],
"AuthToken":"XkWQRd65+H+iPtlOoAEYAR0jrzB1o3UV"}
i have used
jsonstr = new JSONStringer().object().key("Text")
.value(msg).key("Files").array().object().key(
"ContentType").value("image/png").key(
"Content").value(enimg)
.endObject().endArray().key("AuthToken").value(token)
.endObject();
but the server is giving me fault message in return, not accepting the data.
actually i was doing the right thing..everything was OK..
the problem was with org.json package it was not accurate with Base64 string
i switched to another library and all worked..
https://stackoverflow.com/questions/338586/a-better-java-json-library
see the above question for another json libraries
that was problem with org.json
i switched to another..and all it works
nesting too deep in JSON... should I switch to XML?
This is a way to do what you want:
// Creating root JSONObject
JSONObject json = new JSONObject();
// Put in it a String field
json.put("Text", "Hello sample");
// Creating a JSONArray
JSONArray arr = new JSONArray();
//Creating the element to populate the array
JSONObject element = new JSONObject();
element.put("ContentType","image/png");
element.put("Content","iVBORw0K...gDXgARBO/");
// Put it in the array
arr.put(element);
// Put the array and other fileds in the root JSONObject
json.put("Files", arr);
json.put("AuthToken", "XkWQ...o3UV");
// Get the JSON String
String s = json.toString();
// Get formatted and indented JSON String
String s2 = json.toString(4);
// 4 is the number of spaces to indent the string
You can use JSONObject class for this purpose
http://developer.android.com/reference/org/json/JSONObject.html

Categories

Resources