I want to parse json, but I didn't find how to parse array from this structure:
{
"0": {
"title": "\u0417\u041d: \u0415\u0432\u0440\u043e\u043f\u0435\u0439\u0446\u044b ",
"date": "2011-11-26 14:33:00"
},
"1": {
"title": "\u041a\u0430\u043a\u0430\u044f ",
"date": "2011-11-25 13:55:00"
},
"2": {
"title": "\u0423\u043a\u0440\u0430\u0438\u043d\u0430",
"date": "2011-11-25 11:15:00"
},
"3": {
"title": "\u0423\u0416\u0421\u041a ",
"date": "2011-11-24 15:45:00"
},
"time": 0.03944993019104
}
See, the problem is you don't actually have an array. You have a series of dictionaries, keyed by index. The only way to do this is to iterate over each numerical key, and add its value to a list.
Here's some pseudocode to help you get started:
yourArray = new Array(yourJSON.keys.length)
for key in yourJSON.keys:
yourArray.put(yourJSON[key], int(key))
You'll need to make a new array object whose length is equal to the number of keys. Then, put each of the values for each key at index key.
Try parsing these as JSONObject and then accessing it's values keys provided.
To be more specific:
try {
JSONObject foo = new JSONObject(youJsonString);
foo.get(name)
} catch (JSONException e) {
//handle exceptions
}
Related
this below json result sent from server for my app, all_food is object which keys started with string with number such as list1, list2 or list9 and lists nested all_foods have an number for keys, this structure is very difficult for me to know how can i make class structure for that
{
"all_foods": {
"list1": {
"1": "---------------",
"5": "---------------"
},
"list2": {
"1": "---------------",
"3": "---------------"
},
"list9": {
"1": "---------------",
"4": "---------------",
"6": "---------------"
}
},
"show_mixture": false,
"User_status": 2,
"lists": [
{
"UserDailyList": {
"id": "142885",
"created": "2017-08-06 22:12:56",
"modified": "2017-08-06 22:12:56"
},
"foods": {
"1": {
"meal": "---------------",
"food": "---------------"
},
"2": {
"meal": "---------------",
"food": "---------------"
},
"3": {
"meal": "---------------",
"food": "---------------"
}
}
}
],
"error": 1,
"message": "",
"condition": {
"code": "7",
"message": "-------",
"token": 10
}
}
how can i make this structure on java class? Thanks in advance
Well, two ways
You could learn the whole object modelling in Java, create POJO class which contain another class and so on.
Or you could use an online tool create the POJO from any JSON.
Two google search results for you, you can search for
JSON to POJO Online
and check more links there.
Link 1
Link 2
assuming you are using GSON
class FoodResponse{
#SerializedName("all_foods")
Map<String,Map<String,String>> allFood;
#SerializedName("show_mixture")
boolean showMixture;
///.. and so on
}
usually, with such unnecessarily complex and poorly designed JSON I recommend deserializing it like this:
new Gson().fromJson(json, Map.class); //or just Object.class
which returns a LinkedTreeMap of LinkedTreeMaps of LinkedTreeMaps (..n)
which you can browse by key/value and extract the data you need.
You won't be able to create a proper response model for a JSON that hasn't been generated from a proper JSON model on the backend. It is a common practice to fist-fight backend devs to have them send good json :)
//Basic skeleton of pojo class
class AllFoods {
List<String> l1 = new ArrayList<>();
List<String>[] arrayOfList = new List[3]; //In case if we know how //many arraylist items are added,
String show_mixture;
String User_status;
List<String> l1sts = new ArrayList<>();
String UserDailyList;
String id;
String created;
String modified;
List<String> foodsArray= new List[3]; //if we know the range
List<String> foodsList = new ArrayList<>();
String error;
String message;
List<String> condition = new ArrayList<>();
}
//Then we need to have constuctors and add the values and have them in arrayofList
I try to save properties in a Couchbase-document in Android.
The properties hold a JSONArray with several JSONObjects.
When I do document.putproperties(myproperties) a couchbaseliteexception with state 400 and the message "bad or missing json" is thrown".
So the JSONArray looks like:
"some_prop" -> "[
{
"content":"someContent",
"key2":"",
"key3":"",
"key4":"",
"month":8,
"day":3,
"key5":115
},
{
"content":"Some other content",
"key2":"something",
"key3":"",
"key4":"",
"month":8,
"day":3,
"key5":115
}]"
Can anyone tell me whats the problem with this JSON?
EDIT:
the JSONArray with the corresponding key is saved in a hashmap like it is explained in:
http://developer.couchbase.com/mobile/develop/guides/couchbase-lite/native-api/document/index.html
EDIT 2:
The Method where the update is executed and the JSONArray is filled:
private void updateDoc(ArrayList<MyObject> objects) {
Document document = getDocument();
// Update the document with more data
Map<String, Object> updatedProperties = new HashMap<>();
JSONArray objectArray = new JSONArray();
//fill array with data
for(MyObject element : objects) {
JSONObject jsonObjects = element.toJSONObject();
if(jsonObjects != null) {
objectArray.put(jsonObjects);
}
}
//set data to property map
updatedProperties.put(MYOBJECT_PROP_IDENTIFIER, objectArray);
try {
// Save properties to the Couchbase local Couchbase Lite DB
document.putProperties(updatedProperties);
} catch (CouchbaseLiteException e) {
}
}
Not sure if this is what you're looking for,
You can also use something like http://jsonlint.com to verify your son
{
"some_prop": [
{
"content": "someContent",
"key2": "",
"key3": "",
"key4": "",
"month": 8,
"day": 3,
"key5": 115
},
{
"content": "Some other content",
"key2": "something",
"key3": "",
"key4": "",
"month": 8,
"day": 3,
"key5": 115
}
]
}
Finally I found a solution to the problem:
I don't use JSONObject or JSONArray anymore but save my data in ArrayList and put each element directly into the database. so i don't have an Array with all the elements which but a lot of single elements direktly in the document. To accesss them later I save also the number of elements in the DB. Each element has the index as a prefix so it can be identified later on.
That's not quite a nice way but it works..
I am writing a Native Android App in which i am using PHP MYSQL to get data from server Using GET Request.
The way that the server sends me the result is as follows:
{
"result": true,
"error_message": "",
"response": [
{
"total_tasks": 8,
"tasks": [
{
"id": 8,
"name": "Hello Christine, call Mr. Dejan Mandic"
},
{
"id": 7,
"name": "Hello Christine, call Ms. Charente Douglas-Smith"
},
{
"id": 6,
"name": "Hello Christine, call Mrs. Alison Marshall"
},
{
"id": 5,
"name": "Hello Christine, call Mrs. Muna Crisp"
},
{
"id": 4,
"name": "Hello Christine, call Mr. Victor Crisp"
},
{
"id": 3,
"name": "Hello Christine, call Mrs. Kathy Dunn"
},
{
"id": 2,
"name": "Hello Christine, call Mr. Peter Dunn"
},
{
"id": 1,
"name": "Hello Christine, call Ms. Vanessa Allen"
}
]
}
]
}
I need to show the data from the array "respones" -> "tasks" (i.e id and name) in my List View in android and eventually when the user clicks in a particular row in ListView the information about that task is shown in another activity using the id. As the server is sending the data in multidimensional array, I am having problem getting the data in my ListView.
It would be a great help if someone could kindly help me out.
Thank You :)
JSONObject responseObject = new JSONObject(responseString);
boolean resultSuccess = responseObject.getBoolean("result");
if(resultSuccess) {
JSONArray responseArray = responseObject.getJSONArray("response");
JSONObject firstResponse = responseArray.getJSONObject(0);
JSONArray tasks = firstResponse.getJSONArray("tasks");
for(int i = 0; i < tasks.length(); i++){
JSONObject task = tasks.getJSONObject(i);
int id = task.getInt("id");
String name= task.getString("name");
}
}
You just need to navigate through the tree to parse your json although I had some comments on your JSON tree
Why do you have the response as an array? It's only one object
right?
The number of tasks is redundant data you already have the tasks and can infer the length from that.
I have a json object being returned that has multiple arrays within the json object. I am able to parse a json object if it has one array in it (with jObject.getJSONArray("2013-10-30")), but not multiple. The amount of arrays (i.e. the dates) would be changing almost everyday (some days there wouldn't be any) and that is where I get stuck. I'm not sure how to get a list of all the array names and then iterator through that.
{
"2013-10-30": [
{
"id": "399",
"Time": "00:50:46"
}
],
"2013-10-29": [
{
"id": "398",
"Time": "21:44:09"
},
{
"id": "393",
"Time": "10:53:01"
}
]
}
You should iterate over the keys and get the JSONArray for each key as follow:
Iterator<String> keys = jObject.keys();
while(keys.hasNext()){
String key = keys.next();
try{
JSONArray array = jObject.getJSONArray(key);
// do something with the array
// ...
}
catch(Exception e){
e.printStackTrace()
}
}
How can I parse the following to retrieve the following.
{"docs": [
"SolrDocument[{content_type=[text/plain], description=/mnt/sdcard/A.txt, id=4df6fa43-1a99-4475-bc5b-80dd0ab6d114, name=uploadedfile}]",
"SolrDocument[{content_type=[text/plain], description=asdf.png, id=9fb20d5d-cf39-4635-9a22-64560124809e, name=uploadedfile}]"]
}
I need to retrieve description into a string array and id to another string array.
I tried
a="docs"
JSONObject jobj = new JSONObject(line);
JSONArray IDS = (JSONArray) jobj.get(a);
This works but it returns an array of strings
The data you are trying to parse isn't valid JSON, so you are now in RegEx territory. So reading each line out of the JSONArray you could extract what you are after like this:
String data = "SolrDocument[{content_type=[text/plain], description=/mnt/sdcard/A.txt, id=4df6fa43-1a99-4475-bc5b-80dd0ab6d114, name=uploadedfile}]";
Pattern values = Pattern.compile("(description|id)=([\\S]+),", Pattern.CASE_INSENSITIVE);
Matcher matches = values.matcher(data);
while(matches.find()) {
System.out.println(matches.group(1) + "=" + matches.group(2));
}
This will print out:
description=/mnt/sdcard/A.txt
id=4df6fa43-1a99-4475-bc5b-80dd0ab6d114
The elements inside the JSONArray "docs" are not valid JSON objects. You must have "key":"value" pairs in order to be valid.
For example:
{
"docs": [
{
"id": 912345678901,
"text": "How do I read JSON on Android?",
"geo": null,
"user": {
"name": "android_newb",
"followers_count": 41
}
},
{
"id": 912345678902,
"text": "#android_newb just use android.util.JsonReader!",
"geo": [
50.454722,
-104.606667
],
"user": {
"name": "jesse",
"followers_count": 2
}
}
]
}
There are plenty of sites that can validate your JSON, for example JSONLint
Before we can answer your question, fix your JSON.