I want to parse my Json array dynamically. and want to get array of KEYS for each element under jsonarray. i an getting this through iterator. but not getting the sequeance as per the output json formate.
my JSON Formate :
{
"result": "Success",
"AlertDetails": [
{
"ShipmentNumber": "SHP34",
"Customer": "BEST",
"DateCreated": "2012-08-29T04:59:18Z"
"CustomerName": "BEST"
},
{
"ShipmentNumber": "SHP22",
"Customer": "BEST",
"DateCreated": "2012-08-29T05:34:18Z"
"CustomerName": "Jelly"
}
]
}
here is My Code :
JSONArray array = jsonobject.getJSONArray("AlertDetails");
JSONObject keyarray = array.getJSONObject(0);
Iterator temp = keyarray.keys();
while (temp.hasNext()) {
String curentkey = (String) temp.next();
KEYS.add(curentkey);
}
Log.d("Parsing Json class", " ---- KEYS---- " + KEYS);
What i am getting in logcate output:
---- KEYS---- [DateCreated,CustomerName, Customer, ShipmentNumber]
What i want :
---- KEYS---- [ShipmentNumber, Customer, DateCreated,CustomerName]
The JSONObject documentation (link: http://developer.android.com/reference/org/json/JSONObject.html) has the following description for the keys() function:
public Iterator keys ()
Since: API Level 1
Returns an iterator of the String names in this object. The returned
iterator supports remove, which will remove the corresponding mapping
from this object. If this object is modified after the iterator is
returned, the iterator's behavior is undefined. The order of the keys
is undefined.
So you may get the keys but the order is undefined. You may use any of the sorting algorithms if you want the keys in any particular order.
EDIT
Since you are unaware of the order of KEYS you are getting from the WS, after receiving the data you may show the details on screen in an ordered format . After building the arraylist KEYS, you may sort it alphabetically using the following:
Collections.sort(KEYS);
This will order the Strings in the KEYS arraylist according to its natural ordering (which is alphabetically).
I just come to know when I press ctlr+space bar, in which its clearly written that behavior of the keys is undefined, orders is not maintain by keys.
Arun George said# correctly that you have to use any sorting method to achieve your goal.
and for sorting may be this link will help you.
Use GSON library from google. It has a a lot of setting to read/create/parse json array and json objects. I didn't test it to find the solution, but I think it's very simple and full featured tool and can solve the problem.
Use different library to parse json dynamically.
Below I wrote a piece of code based on Jackson JSON Processor, which is the best JSON library in my opinion
public void test() throws IOException {
String str = "{\n" +
" \"result\": \"Success\",\n" +
" \"AlertDetails\": [\n" +
" {\n" +
" \"ShipmentNumber\": \"SHP34\",\n" +
" \"Customer\": \"BEST\",\n" +
" \"DateCreated\": \"2012-08-29T04:59:18Z\",\n" +
" \"CustomerName\": \"BEST\"\n" +
" }\n" +
" ]\n" +
"}";
JsonFactory factory = new JsonFactory();
JsonParser jsonParser = factory.createJsonParser(str);
JsonToken jsonToken;
SerializedString alertDetails = new SerializedString("AlertDetails");
while (!jsonParser.nextFieldName(alertDetails)) { /* move to AlertDetails field */ }
jsonParser.nextToken(); // skip [ start array
jsonParser.nextToken(); // skip { start object
// until } end object
while ((jsonToken = jsonParser.nextToken()) != JsonToken.END_OBJECT) {
if (jsonToken == JsonToken.FIELD_NAME) {
System.out.println(jsonParser.getCurrentName());
}
}
}
It simply prints out field names in the same order as in json:
ShipmentNumber
Customer
DateCreated
CustomerName
EDIT
Naturally you can use other libraries like gson etc. But remember, as is written on json.org, that:
An object is an unordered set of name/value pairs.
and the order of keys depends on implementation and might vary in each request.
There is also the method names();
Returns an array containing the string names in this object.
Edit: returns names in undefined order. Suggestions: parse it on your own
Related
How to send GET request with query params like this?
key1=["S","I","D"]&key2=[["A","X",0],["X","Y","Z"]]
According to retrofit java documents, you can do like below.
Values are converted to strings using Retrofit.stringConverter(Type, Annotation[]) (or Object.toString(), if no matching string converter is installed) and then URL encoded. null values are ignored. Passing a List or array will result in a query parameter for each non-null item.
Array/Varargs Example:
#GET("/friends")
Call<ResponseBody> friends(#Query("group") String... groups);
Calling with foo.friends("coworker", "bowling") yields /friends??> group=coworker&group=bowling.
So you can do something like this
#GET("/something")
Call<ResponseBody> getSomething(#Query("key1") String[] key1,
Query("key2") String[] key2 );
foo.getSomething(key1, key2)
Update - above is the standard way to query parameters with multiple values
In order to send array as string, you can do like below
Parameter names and values are URL encoded by default. Specify encoded=true to change this behavior.
#GET("/something")
Call<ResponseBody> getSomething(#Query(value="key1", encoded=true) String key1);
Calling with foo.getSomething("['S','I','D']")) yields /something?key1=['S','I','D'].
Since retrofit doesn't recognize your custom array type, you have to consider parameters type String, then build your parameter like "["S","I","D"]" before pass to retrofit method.
For example create your parameter:
String parameter = "["
int arraySize = array.size()
for(int i = 0; i < arraySize; i++) {
parameter += "\"" + array.get(i) + "\"";
if(i != arraySize - 1) {//Append ',' except last element
parameter += ",";
}
}
parameter += "]";
Output for array with 'S','I' and 'D' elements is ["S","I","D"] String.
Now you can pass it as retrofit parameter.
I have to parse api about cryptocurrency exchange. It includes cryptocurrency named "TRUE", and makes JSONException. Well... JSONObject cognize "TRUE" as Boolean data. 😂 JSONObject have probably seen "TRUE=" as a comparison of Boolean values. That makes me seriously laugh, and was very funny but obviously is problem I have to solve. How to parse Json having "TRUE" as key name? It's okay if solution is using Gson.
https://api.bithumb.com/public/ticker/ALL_KRW
This is API link.
String s= "
"TRUE" : {
"opening_price":"394.4"
}
"
JSONObject jsonObject = new JSONObject("{" + s +"}");
Log.d("JSON",jsonObject.getJSONObject("TRUE").getString("opening_price"));
I'd quickly explain what's going on in the JSON data above;
I have a table called messages, with some messages having a common message_id column. I grouped the messages by message_id. the boxes in red are the message_id's which have children
Now onto the question;
is it possible to access the children of the various arrays of message_id, without actually using the message_id string?
i.e iterate over the arrays
while (i < array.length) {
array[i]
}
if it's possible how can I do it?
Below is how I currently get the first array from the data object using the array id exactly
val jsonObject = JSONObject(response)
if (!jsonObject.getBoolean("error")) {
//getting data array from json response object
val dataObject = jsonObject.getJSONObject("data")
Log.i("MessageFragment", "[][] data array " + dataObject)
val array = dataObject.getJSONArray("NzbyxhmodN")
var i = 0
while (i < array.length()) {
//getting wallet object from json array
val message = array.getJSONObject(i)
//adding the wallet to wallet list
messageList!!.add(Message(
message.getInt("id"),
message.getInt("sender_id"),
message.getInt("receiver_id"),
message.getString("subject"),
message.getString("message"),
message.getString("message_id"),
message.getString("timestamp"),
message.getBoolean("isRead")
))
i++
}
I want to get the arrays without using the name i.e ("NzbyxhmodN")
Unfortunately, you cannot model without knowing the key value.
In such cases, I use this approach. It will be useful to you.
// data -> server json response
Iterator keys = data.keys();
while(keys.hasNext()) {
// random key
String key = (String)keys.next();
// and value...
JSONArray value = data.getJSONArray(key);
}
I am trying to display data from a rest api containing a Json Array and a list of Json objects. I tried following a tutorial and was able to display the data on textview. What I actually want to do is gather the data in a Hashmap in terms of key and value pair and sort them accordingly.
public void onResponse(Call<List<Post>> call, Response<List<Post>> response) {
if(!response.isSuccessful()){
textView.setText("Code: " +response.code());
return;
}
int j=0;
List<Post> posts = response.body();
Map<Integer,String> data = new HashMap<Integer, String>();
// Iterating through post and saving data in content variable
for(Post post: posts)
{
String content ="";
//String name = post.getName();
if(!(post.getName()==(null)) && !(post.getName().equals("")))
{
data.put(post.getListid(),post.getName()); //For inserting data into hashmap
content += "ListID: " + post.getListid() + "" + "\n";
content += "Name: " + post.getName() + "" + "\n";
}
textView.append(content);
}
The current code saves the data in a content variable and displays it in the text view.
I am relatively new to using hashmap and retrofit for displaying data. I would really appreciate if someone could explain me where I am going wrong with my code. I tried printing out the data but was only able to print the last line and not the rest.
This is my Json file that I want to sort and display the data
[{"listId":2,"name":null},{"listId":2,"name":"Item 990"},{"listId":2,"name":null},{"listId":2,"name":null},{"listId":2,"name":""},{"listId":4,"name":"Item 771"},{"listId":2,"name":""}]
This is the code that I am using to displaying all my json data in textview
for(Map.Entry entry: data.entrySet())
{ textView.append(entry.getKey()+ " Value:" +entry.getValue() +"\n");}
I if understand correctly, you have a List<Post> posts that you want to sort out ? Why don't you sort the posts as you need and save them accordingly? You could just remove the post from your list if their name are null or ""
I have a JSON Like this
{ "video":{
"video_3745":{ },
"video_3437":{ },
"video_3471":{ },
"video_4114":{ }
}
}
In which every "video_xxxx" is of the SAME type. Is there a way to treat the "video" field as an array of that type? I need to iterate over all the videos, but the API is not sending them in an array, and I don't know how to model a class to receive this JSON without having to manually specify all the field names...
does GSON or LoganSquare have anything to help me out with this?
Try something like this
JSONObject video= json.getJSONObject("video"); // json is the whole response
Iterator x = video.keys();
JSONArray jsonArray = new JSONArray();
while (x.hasNext()){
String key = (String) x.next();
jsonArray.put(video.get(key));
}
You can't treat them as an array, but with the org.json.JSONObject class you can get the list of keys and iterate over them. I believe in GSON the JsonObject.entrySet method will allow something similar.
https://developer.android.com/reference/org/json/JSONObject.html
https://google.github.io/gson/apidocs/com/google/gson/JsonObject.html