Saving and loading multidimensional arrays using Json in Android - android

I am writing an android app that has several large multi-dimensional arrays of data like float[][][][], which should be loaded at the beginning of application run. So I need to read and load them from files, stored in phone storage.
The problem I have with typical solution of reading from files, is that it takes so long to read and load all of them and I am looking for a faster option.
I decided to give a try to Json for mentioned purpose, but I couldn't find any way to store multi-dimensional arrays like float[][][][]. Can anybody propose any clues to help me? Also if you know a better solution rather than Json for my situation, I would really appreciate to hear.
Thanks

A multidimensional array is simply an array of arrays of arrays (repeat for additional dimensions).
Creating a 2d array of floats would go something like this:
float[][] array; // your array
JSONArray outerJsonArray = new JsonArray();
for (int i=0; i < array.length; i++) {
JSONArray innerJsonArray = new JsonArray();
for (int j=0; j < array[i].length; j++) innerJsonArray.put(array[i][j]);
outerJsonArray.put(innerJsonArray);
}
To convert higher dimensional arrays to json, you simply increase the nesting of the loop to match the dimensionality of the array.

Related

Extracting data from JSON array?

{"result":[{"FullName":"Upasiri"}]}
This is what i get when i run my php. I tried doing various things like put this ti a JSONObject and use get methods, but nothing works :/ How can i extract the "Upasiri" from that? Im new to android, so any help is very much appreciated!
Generate POJO classes with http://www.jsonschema2pojo.org/ (for example), then you can use any JSON serializer to get the Java Objects and get FullName from it. Example how to do it with a GSON you can find here - http://www.javacreed.com/simple-gson-example/
This is your answer
JSonArray array = object.getJSonArray ("result");
for (int i=0; i<array.lenght(); i++) {
JSONObject object= array.getJSONObject(i);
// this is your uripase
String url = object.getString("FullName");
}

Iterating through JSONObjects

I have tried several of the examples listed and none of them seem to work for some reason so I am posting a new question.
I have a JSON string coming to me however it is all objects (it is not formatted in an array). I need to parse out the Team names from this. I know I need to iterate over them as they are the keys and then store the objects in a new array.
Here is the JSON (a sample of it)
{"query":{"printrequests":[{"label":"","typeid":"_wpg","mode":2,"format":false}],"results":{"Team:Kubbchucks":{"printouts":[],"fulltext":"Team:Kubbchucks","fullurl":"http://wiki.planetkubb.com/wiki/Team:Kubbchucks","namespace":822,"exists":true},"Team:Kubbchucks
IDP":{"printouts":[],"fulltext":"Team:Kubbchucks
IDP","fullurl":"http://wiki.planetkubb.com/wiki/Team:Kubbchucks_IDP","namespace":822,"exists":true}},"serializer":"SMW\Serializers\QueryResultSerializer","version":0.5,"meta":{"hash":"8407a177d701d746edc3066a012c17d2","count":2,"offset":0}}}
What I have so far to dig down to that level of the JSON (data is the string above)
JSONObject parsing = new JSONObject(data);
JSONObject query = parsing.getJSONObject("query");
JSONObject results = query.getJSONObject("results");
This allows me to manually check for a team using :
JSONObject teamone = results.getJSONObject("Team:Kubbchucks");
This is of course not ideal. The full JSON file has almost 3000 entries and I do not know what those entries all are. I need to iterate over the results object to get the keys that start with "Team:"
I've tried a few different iterator samples but none seem to be working for me and it is starting to really frustrate me. Believe me, I've tried many things before asking the question. Any help is appreciated.
I had a similar problem some time ago.
You can do like this:
JSONObject results = query.getJSONObject("results");
Iterator<String> iterator = results.keys();
while (iterator.hasNext()) {
JSONObject team = results.getJSONObject(iterator.next());
// do stuff
}

Android : how to get jsonarray from json object in different ways

I know how to get jsonarray from jsonobject. I am doing like below code to get jsonarray.
JSONObject recvJson = new JSONObject(holder.toString());
String numberByte= (String) recvJson.get("data");
String ts = (String) recvJson.get("time");
JSONObject temp2 = new JSONObject("{ \"data\" : " + numberByte+ "}");
JSONArray recvJarray = temp2.getJSONArray("data");
for (int i = 0; i < recvJarray.length(); i++)
{
byteArray[i] = (byte) recvJarray.getInt(i);
}
But don't want to use for-loop, without using for-loop or any other loop want to retrieve jsonarray data values.
How should I do ?? I have done google & saw many forums but dint succeed to retrieve data without using for-loop.
for example : I ll be getting 80 - 100 packets of 1024bytes per second from server, I want to retrieve this data & store it into bytearray. By usingf for-loop its taking around 300ms- 400ms and I am loosing many packets between that. So I want to use different approach. If any Idea or solution for cracking this.
Help will be appreciated !!
You can use GSON to parse the json objects. It is much faster and easier to decode json data.
Check these links.
Gson1, Gson2
try usig gson
it uses java reflection to convert objects to json and json to object with simple methods
toJson(),fromJson() (and it works for object arrays and lists too)
but you have to write the proper classes for the jsons (with all fields)
read the documentation.

How to decode an array of array elements in Android

A PHP script is sending to an Android app some data in the following format
[{"event_id":"4","message":"test"},["person1","person2"]]
I want to exact the 2 elements from this array into other arrays so I can easily manipulate the data. I got to the point in which the above response from the server is being converted into as string. What I can't seem to be able to do is to parse the data into arrays. I'm trying something on the following lines:
receivedData = new JSONArray(result); //result is the string response from the server
JSONArray array1= receivedData.getJSONArray(0);
JSONArray array2= receivedData.getJSONArray(1);
int len = array1.length();
but lenis not giving me back anything :(
What am I doing wrong and how could I change it.
Many thanks
What if you start by invoking new JSONObject(result); and then pulling an array out of that? I suspect you're trying to pull an array out of something that is not an array. Your PHP should not return something wrapped in [ ] it should return it wrapped in { }... also I believe your third JSON element (the array itself) is just hanging about without a label, which I believe is illegal.
so...
if your php produced this:
{"event_id":"4","message":"test"},"people": ["person1","person2"]}
and your java was this:
JSONObject j = new JSONObject(result);
String [] people = j.getJSONArray("people");
I believe you'd have what you are after.

Getting specific value from JSONArray

noob Android/JSON person here. I hope someone might help me?
I've looked and looked but don't think it's what I'm after. I've been working on this project all day so maybe my brain has just gone to mush... If this has been awnsered else where please point me that way :)
Anyway, I wish to get a specific object from within an JSONArray - here's what's happening so far:
JSONArray jArray = new JSONArray(result);
for(int i=0;i<jArray.length();i++){
JSONObject json_obj = jArray.getJSONObject(i);
name = json_obj.getString("txt_title");
}
txt_title.setText(name);
As far as I understand result returns the entire JSONArray, then I go through the length of those results using the for loop and get the json objects. At the moment I'm only asking for values from "txt_title" in the Array. So far, so good?
Then what I want to do is, say only set the third "txt_title" value from the Array.
At the moment I would expect txt_title.setText(name) to be displaying ALL the titles in "txt_title" however it's only displaying the LAST title in the Array. This probably has something to do with the for loop?
How would I go about choosing which object is displayed?
You are only displaying the last one in the list right now because you are setting name each time in the loop.
name = json_obj.getString("txt_title");
this overwrites the previous value every time you iterate. If you want to have all the values, you would have to do it in an additive way.
name += json_obj.getString("txt_title");
If you want to get a specific item from the array you just need to access it using the index you want instead of a loop.
if(jArray.length() > 2) {
JSONObject json_obj = jArray.getJSONObject(2); //get the 3rd item
name = json_obj.getString("txt_title");
}
Hope that helps you understand how to access it.
If you can ensure that the element will exist at the index you can skip the loop entirely.
JSONArray jArray = new JSONArray(result);
String name = jArray.getJSONObject(2).getString("txt_title");
txt_title.setText(name);

Categories

Resources