I am trying to store data gotton from JSON to an normal string array. The problem is i cant seem to initialize the array size according to the number for JSON data.
For now i declare the array size my own:
String[] path= new String[5];
This is the JSON part:
class Loadpath extends AsyncTask {
protected String doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
// getting JSON string from URL
JSONObject json = jParser.makeHttpRequest(url_all_imageDB, "GET",params);
try {
JSONArray productObj = json.getJSONArray(TAG_IMAGEDB); // JSON Array
// looping through All path
for (int i = 0; i < productObj.length(); i++) {
JSONObject image = productObj.getJSONObject(i);
path[i] = image.getString(TAG_PATH);
}
} else {
displayPath.setText("No path");
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
So my goal is the array size is gotten from the JSON.length().. Any idea how I can achieve this?
initialize the mStrings[ ] array size according to the JSONArray length as:
String[] mStrings; //<< Declare array as
mStrings = new String[productObj.length()]; //<<initialize here
for (int i = 0; i < productObj.length(); i++) {
JSONObject image = productObj.getJSONObject(i);
mStrings[i] = image.getString(TAG_PATH);
}
and it is good if you use ArrayList instead of String Array as for getting values from Jsonobject as:
ArrayList<String> mStrings=new ArrayList<String>(;
for (int i = 0; i < productObj.length(); i++) {
JSONObject image = productObj.getJSONObject(i);
mStrings.add(image.getString(TAG_PATH));
}
Maybe u can use List instead of String array
Related
I have Java program and I am reading from file of Size Approx 40GB and converting data on fly and streaming to DataOutputstream.
Below is my code
JSONObject jsonObj= new JSONObject();
JSONArray jsonArray = new JSONArray();
JSONObject properties = new JSONObject();
while((strLine = in.readLine()) != null)
{
if (jsonArray.length()%100 == 0) {
printJsonData(jsonArray);
// sendJsonData(jsonArray, output);
jsonArray = new JSONArray();
}
if (strLine.trim().contains("data")) {
jsonObj.put("properties",properties);
jsonArray.put(jsonObj);
if (strLine.trim().contains("data1")) {
String secondPart = strLine.split(":",2)[1];
properties.put("data1", secondPart);
continue;
}
if (strLine.trim().contains("id")) {
String secondPart = strLine.split(":",2)[1];
jsonObj.put("id", secondPart );
continue;
}
}
I have two methods one is printing JSON data and other is sending Json data over https.
private void printJsonData(JSONArray jsonArray) {
int count = jsonArray.length(); // get totalCount of all jsonObjects
for(int i=0 ; i< count; i++){ // iterate through jsonArray
JSONObject jsonObject = jsonArray.getJSONObject(i); // get jsonObject # i position
System.out.println("jsonObject " + i + ": " + jsonObject);
}
}
private void sendJsonData(JSONObject jsonObj,DataOutputStream output) throws IOException {
int count = jsonArray.length();
for(int i=0 ; i< count; i++) { // iterate through jsonArray
JSONObject jsonObject = jsonArray.getJSONObject(i); // get jsonObject # i position
System.out.println("Sending Data-->" + jsonObject.toString());
output.writeBytes(jsonObject.toString());
}
}
Whenver i call print method, every thing works fine. But when i call sendJsonData method. I am getting OutofMemoryerror. Wondering how to fix it?
Since you are not manipulating json in any way I would treat as a text file and send it that way. The likelihood of finding a big JsonObject is good so you may be pushing through too much.
An array of 40gb is awfully big array unless there are huge objects.
** EDIT **
Or you could treat the individual json objects as "files" and push those strings individually
I get JSON from a rest server (jax rs) through a http request.
[{"carId":"t0","movements":[{"edge":{"edgeId":"--104","fromNode":{"latitude":"51.404456094285734","longitude":"5.477570348298111","nodeId":"-16"},"lanes":[{"laneId":"--104_0"},{"laneId":"--104_1"}],"toNode":{"latitude":"51.404057790546894","longitude":"5.424575687577547","nodeId":"-14"}},"id":8,"lane":{"laneId":"--104_0"},"position":73.76,"speed":14.49,"timeStep":8.0},{"edge":{"edgeId":"--104","fromNode":{"latitude":"51.404456094285734","longitude":"5.477570348298111","nodeId":"-16"},"lanes":[{"laneId":"--104_0"},{"laneId":"--104_1"}],"toNode":{"latitude":"51.404057790546894","longitude":"5.424575687577547","nodeId":"-14"}},"id":16,"lane":{"laneId":"--104_0"},"position":89.35,"speed":15.59,"timeStep":9.0},{"edge":{"edgeId":"--104","fromNode":{"latitude":"51.404456094285734","longitude":"5.477570348298111","nodeId":"-16"},"lanes":[{"laneId":"--104_0"},{"laneId":"--104_1"}],"toNode":{"latitude":"51.404057790546894","longitude":"5.424575687577547","nodeId":"-14"}},"id":27,"lane":{"laneId":"--104_0"},"position":106.39,"speed":17.03,"timeStep":10.0},{"edge":{"edgeId":"--104","fromNode":{"latitude":"51.404456094285734","longitude":"5.477570348298111","nodeId":"-16"},"lanes":[{"laneId":"--104_0"},{"laneId":"--104_1"}],"toNode":{"latitude":"51.404057790546894","longitude":"5.424575687577547","nodeId":"-14"}},"id":35,"lane":{"laneId":"--104_0"},"position":125.24,"speed":18.85,"timeStep":11.0},{"edge":{"edgeId":"--104","fromNode":{"latitude":"51.404456094285734","longitude":"5.477570348298111","nodeId":"-16"},"lanes":[{"laneId":"--104_0"},{"laneId":"--104_1"}],"toNode":
Just to give you an idea how the JSON looks like.
Now I want to convert every item of this JSON file to an Java object.
So I want to see inside the "fromNode" to get the attributes to make an object.
I can see all the movement and edges, thats no problem (i do that like this):
String jsonStringMike = callURL("http://----------/");
try {
JSONArray jsonArrayMike = new JSONArray(jsonStringMike);
int countMike = jsonArrayMike.length(); // get totalCount of all jsonObjects
for (int i = 0; i < countMike; i++) { // iterate through jsonArray
JSONObject jsonObject = jsonArrayMike.getJSONObject(i); // get jsonObject # i position
JSONArray movement = jsonObject.getJSONArray("movements");
String edge = movement.getJSONObject(i).getString("edge");
System.out.println(edge);
So this provides me with all the "edge's" From the JSON file shown before. But if I want to see the "fromNode" I get the following error:
org.json.JSONException: JSONObject["edge"] is not a JSONArray.
This is the code that is not working and will provide the given error.
public static void main(String[] args) throws IOException, JSONException {
String jsonStringMike = callURL("http://6--------------");
try {
JSONArray jsonArrayMike = new JSONArray(jsonStringMike);
int countMike = jsonArrayMike.length(); // get totalCount of all jsonObjects
for (int i = 0; i < countMike; i++) { // iterate through jsonArray
JSONObject jsonObject = jsonArrayMike.getJSONObject(i); // get jsonObject # i position
JSONArray movement = jsonObject.getJSONArray("movements");
int o = movement.length();
String test = movement.toString();
JSONArray jsonArray2 = new JSONArray(test);
for (int p = 0; p < o; o++) {
JSONObject moveObject = jsonArray2.getJSONObject(p);
JSONArray edge = moveObject.getJSONArray("edge");
String fromNode = edge.getJSONObject(p).getString("fromNode");
System.out.println(fromNode);
}
Does anybody knows how I can look "deeper" into the given JSON file?
I think you are almost there, the issue in your code that in the loop moveObject is your edge json object, so movemen.length() is the the count of all edge json objects in the array. I have not tested this, but I think it should work. Also, your for loop has typo, o++ should be p++,
JSONArray jsonArrayMike = new JSONArray(jsonStringMike);
int countMike = jsonArrayMike.length(); // get totalCount of all jsonObjects
for (int i = 0; i < countMike; i++) { // iterate through jsonArray
JSONObject jsonObject = jsonArrayMike.getJSONObject(i); // get jsonObject # i position
JSONArray movement = jsonObject.getJSONArray("movements");
int o = movement.length();
for (int p = 0; p < o; p++)
{
JSONObject movementObject = movement.getJSONObject(p);
JSONObject edgeObject = movementObject.getJSONObject("edge");
JSONObject fromNode = edgeObject.getJSONObject("fromNode");
String latitude = fromNode.getString("latitude");
String longitude = fromNode.getString("longitude");
String nodeId = fromNode.getString("nodeId");
System.out.println(fromNode);
}
}
I have a webservice which returns a JSON array in this format:
[{"imageid":"3","userid":"1","imagepath":"SLDFJNDSKJFN","filterid":"1","dateadded":"2014-05-06 21:20:18.920257","public":"t"},
{"imageid":"4","userid":"1","imagepath":"dsfkjsdkfjnkjdfsn","filterid":"1","dateadded":"2014-05-06 21:43:37.642748","public":"t"}]
I need to get all the attributes seperately? How would I do this?
I know how to do it with JSONObject if there is just 1 thing being returned, but how does it work when multiple items are returned?
Thanks
try {
JSONArray jArray = new JSONArray(jsonString);
String s = new String();
for (int i = 0; i < jArray.length(); i++) {
s = jArray.getJSONObject(i).getString("imageid").toString();
s = jArray.getJSONObject(i).getString("userid").toString();
}
} catch (JSONException je) {
}
Create an Object class with all variables, create a List for this Object, add all objects in your JSONArray to the list, use the one you need.
List<YourObject> objList = new ArrayList<YourObject>();
JSONArray a = new JSONArray(response);
int size = a.length();
for (int i=0 ; i<size ; i++){
JSONObject aa = a.getJSONObject(i);
String id = aa.getString("imageid");
String userid = aa.getString("userid");
String imagepath = aa.getString("imagepath");
String filterid = aa.getString("filterid");
String dateadded = aa.getString("dateadded");
String publicText = aa.getString("public");
YourObject obj = new YourObject(id,userid,imagepath,filterid,dateadded,publicText);
objList.add(obj);
}
So what you are having here is some JSON objects inside a JSON array.
What you want to do is this:
JSONArray array = ...;
for (int i = 0; i < array.length(); i++) {
JSONObject o = array.getJSONObject(i);
// Extract whatever you want from the JSON object.
}
I hope it helped.
You can use JSONArray to parse array of JSON response.
private void parseJsonArray(String response) {
try {
JSONArray array = new JSONArray(response);
for(int i=0;i<array.length();i++){
JSONObject jsonObject = array.getJSONObject(i);
String ImageId = jsonObject.getString("imageid");
Log.v("JSON Parser", "ImageId: "+ImageId);
}
} catch (Exception e) {
e.printStackTrace();
}
}
JSONArray jsonArray = new JSONArray();
jsonArray.put(1);
jsonArray.put("empty");
jsonArray.put(2);
jsonArray.put(3);
jsonArray.put("empty");
jsonArray.put(4);
jsonArray.put("empty");
lets say we have this jsonArray, there are strings empty, how to remove them without leaving gaps?
You can use the following code :
for (int i = 0, len = jsonArray.length(); i < len; i++) {
JSONObject obj = jsonArray.getJSONObject(i);
String val = jsonArray.getJSONObject(i).getString();
if (val.equals("empty")) {
jsonArray.remove(i);
}
}
take a look at this post.
Make a list to put the indexes of the elements with the "empty" string and iterate over your list (the one with the "empty" elements) saving the indexes of the items to delete. After that, iterate over the previosly saved indexes and use
list.remove(position);
where position takes the value of every item to delente (within the list of index).
Should work with few fixes to Keerthi's code:
for (int i = 0; i < jsonArray.length(); i++) {
if (jsonArray.get(i).equals("empty")) {
jsonArray.remove(i);
}
}
You can use this following code
JSONArray list = new JSONArray();
JSONArray jsonArray = new JSONArray(jsonstring);
int len = jsonArray.length();
if (jsonArray != null) {
for (int i=0;i<len;i++)
{
//Excluding the item string equal to "empty"
if (!"empty".equals(jsonArray.getString(i))
{
list.put(jsonArray.get(i));
}
}
//Now, list JSONArray has no empty string values
}
you can use string replace after converting the array to string as,
JSONArray jsonArray = new JSONArray();
jsonArray.put(1);
jsonArray.put("empty");
jsonArray.put(2);
jsonArray.put(3);
jsonArray.put("empty");
jsonArray.put(4);
jsonArray.put("empty");
System.err.println(jsonArray);
String jsonString = jsonArray.toString();
String replacedString = jsonString.replaceAll("\"empty\",", "").replaceAll("\"empty\"", "");
jsonArray = new JSONArray(replacedString);
System.out.println(jsonArray);
Before replace:
jsonArray is [1,"empty",2,3,"empty",4,"empty"]
After replace:
jsonArray is [1,2,3,4]
Is there a way to convert JSON Array to normal Java Array for android ListView data binding?
ArrayList<String> list = new ArrayList<String>();
JSONArray jsonArray = (JSONArray)jsonObject;
if (jsonArray != null) {
int len = jsonArray.length();
for (int i=0;i<len;i++){
list.add(jsonArray.get(i).toString());
}
}
If you don't already have a JSONArray object, call
JSONArray jsonArray = new JSONArray(jsonArrayString);
Then simply loop through that, building your own array. This code assumes it's an array of strings, it shouldn't be hard to modify to suit your particular array structure.
List<String> list = new ArrayList<String>();
for (int i=0; i<jsonArray.length(); i++) {
list.add( jsonArray.getString(i) );
}
Instead of using bundled-in org.json library, try using Jackson or GSON, where this is a one-liner. With Jackson, f.ex:
List<String> list = new ObjectMapper().readValue(json, List.class);
// Or for array:
String[] array = mapper.readValue(json, String[].class);
Maybe it's only a workaround (not very efficient) but you could do something like this:
String[] resultingArray = yourJSONarray.join(",").split(",");
Obviously you can change the ',' separator with anything you like (I had a JSONArray of email addresses)
Using Java Streams you can just use an IntStream mapping the objects:
JSONArray array = new JSONArray(jsonString);
List<String> result = IntStream.range(0, array.length())
.mapToObj(array::get)
.map(Object::toString)
.collect(Collectors.toList());
Use can use a String[] instead of an ArrayList<String>:
It will reduce the memory overhead that an ArrayList has
Hope it helps!
String[] stringsArray = new String[jsonArray.length()];
for (int i = 0; i < jsonArray.length; i++) {
parametersArray[i] = parametersJSONArray.getString(i);
}
I know that question is about JSONArray but here's example I've found useful where you don't need to use JSONArray to extract objects from JSONObject.
import org.json.simple.JSONObject;
import org.json.simple.JSONValue;
String jsonStr = "{\"types\":[1, 2]}";
JSONObject json = (JSONObject) JSONValue.parse(jsonStr);
List<Long> list = (List<Long>) json.get("types");
if (list != null) {
for (Long s : list) {
System.out.println(s);
}
}
Works also with array of strings
Here is a better way of doing it: if you are getting the data from API. Then PARSE the JSON and loading it onto your listview:
protected void onPostExecute(String result) {
Log.v(TAG + " result);
if (!result.equals("")) {
// Set up variables for API Call
ArrayList<String> list = new ArrayList<String>();
try {
JSONArray jsonArray = new JSONArray(result);
for (int i = 0; i < jsonArray.length(); i++) {
list.add(jsonArray.get(i).toString());
}//end for
} catch (JSONException e) {
Log.e(TAG, "onPostExecute > Try > JSONException => " + e);
e.printStackTrace();
}
adapter = new ArrayAdapter<String>(ListViewData.this, android.R.layout.simple_list_item_1, android.R.id.text1, list);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// ListView Clicked item index
int itemPosition = position;
// ListView Clicked item value
String itemValue = (String) listView.getItemAtPosition(position);
// Show Alert
Toast.makeText( ListViewData.this, "Position :" + itemPosition + " ListItem : " + itemValue, Toast.LENGTH_LONG).show();
}
});
adapter.notifyDataSetChanged();
adapter.notifyDataSetChanged();
...
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;
}
You can use a String[] instead of an ArrayList<String>:
Hope it helps!
private String[] getStringArray(JSONArray jsonArray) throws JSONException {
if (jsonArray != null) {
String[] stringsArray = new String[jsonArray.length()];
for (int i = 0; i < jsonArray.length(); i++) {
stringsArray[i] = jsonArray.getString(i);
}
return stringsArray;
} else
return null;
}
We can simply convert the JSON into readable string, and split it using "split" method of String class.
String jsonAsString = yourJsonArray.toString();
//we need to remove the leading and the ending quotes and square brackets
jsonAsString = jsonAsString.substring(2, jsonAsString.length() -2);
//split wherever the String contains ","
String[] jsonAsStringArray = jsonAsString.split("\",\"");
To improve Pentium10s Post:
I just put the elements of the JSON array into the list with a foreach loop. This way the code is more clear.
ArrayList<String> list = new ArrayList<String>();
JSONArray jsonArray = (JSONArray)jsonObject;
jsonArray.forEach(element -> list.add(element.toString());
private String[] getStringArray(JSONArray jsonArray) throws JSONException {
if (jsonArray != null) {
String[] stringsArray = new String[jsonArray.length()];
for (int i = 0; i < jsonArray.length(); i++) {
stringsArray[i] = jsonArray.getString(i);
}
return stringsArray;
} else
return null;
}
You can use iterator:
JSONArray exportList = (JSONArray)response.get("exports");
Iterator i = exportList.iterator();
while (i.hasNext()) {
JSONObject export = (JSONObject) i.next();
String name = (String)export.get("name");
}
I know that the question was for Java. But I want to share a possible solution for Kotlin because I think it is useful.
With Kotlin you can write an extension function which converts a JSONArray into an native (Kotlin) array:
fun JSONArray.asArray(): Array<Any> {
return Array(this.length()) { this[it] }
}
Now you can call asArray() directly on a JSONArray instance.
How about using java.util.Arrays?
List<String> list = Arrays.asList((String[])jsonArray.toArray())