I expected to find this question around, but I couldn't. Maybe I'm Googling the wrong thing.
I have a primitive integer array (int[]), and I want to convert this into a String, that is "JSON-Parseable", to be converted back to the same int[].
What have I tried :
I tried this code :
// int[] image_ids_primitive = ...
JSONArray mJSONArray = new JSONArray(Arrays.asList(image_ids_primitive));
String jSONString = mJSONArray.toString();
Prefs.init(getApplicationContext());
Prefs.addStringProperty("active_project_image_ids", jSONString);
// Note: Prefs is a nice Class found in StackOverflow, that works properly.
When I printed the jSONString variable, it has the value : ["[I#40558d08"]
whereas, I expected a proper JSON String like this : {"1" : "424242" , "2":"434343"} not sure about the quotation marks, but you get the idea.
The reason I want to do this :
I want to keep track of local images (in drawable folder), so I store their id's in the int array, then I want to store this array, in the form of a JSON String, which will be later parsed by another activity. And I know I can achieve this with Intent extras. But I have to do it with SharedPreferences.
Thanks for any help!
You don't have to instantiate the JSONArray with Arrays.asList. It can take a normal primitive array.
Try JSONArray mJSONArray = new JSONArray(image_ids_primitive);
If you are using an API level below 19, one easy method would just be to loop over the int array and put them.
JSONArray mJSONArray = new JSONArray();
for(int value : image_ids_primitive)
{
mJSONArray.put(value);
}
Source: Android Developers doc
If you want a JSON array and not necessarily an object, you can use JSONArray.
Alternatively, for a quick hack:
System.out.println(java.util.Arrays.toString(new int[]{1,2,3,4,5,6,7}));
prints out
[1, 2, 3, 4, 5, 6, 7]
which is valid JSON. If you want anything more complicated than that, obviously JSONObject is your friend.
Try this way
int [] arr = {12131,234234,234234,234234,2342432};
JSONObject jsonObj = new JSONObject();
for (int i = 0; i < arr.length; i++) {
try {
jsonObj.put(""+(i+1), ""+arr[1]);
} catch (Exception e) {
}
}
System.out.println("JsonString : " + jsonObj.toString());
// If you wants the data in the format of array use JSONArray.
JSONArray jsonarray = new JSONArray();
//[1,2,1,] etc..
for (int i = 0; i < data.length; i++) {
jsonarray.put(data[i]);
}
System.out.println("Prints the Json Object data :"+jsonarray.toString());
JSONObject jsonObject=new JSONObject();
// If you want the data in key value pairs use json object.
// i.e {"1":"254"} etc..
for(int i=0;i<data.length;i++){
try {
jsonObject.put(""+i, data[i]);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.out.println("Prints the Json Object data :"+jsonObject.toString());
itertate this through the int array and you will get the json string
JSONStringer img = null ;
img = new JSONStringer() .object() .key("ObjectNAme")
.object() .key("something").value(yourIntarrayAtIndex0)
.key("something").value(yourIntarrayAtIndex1) .key("something").value(yourIntarrayAtIndex2)
.key("something").value(yourIntarrayAtIndex3)
.endObject() .endObject();
String se = img.toString();
Here se is your json string in string format
This code will achieve what you are after...
int index = 0;
final int[] array = { 100, 200, 203, 4578 };
final JSONObject jsonObject = new JSONObject();
try {
for (int i : array) {
jsonObject.put(String.valueOf(index), String.valueOf(i));
index++;
}
} catch (JSONException e) {
e.printStackTrace();
}
Log.d("YOUR_TAG", jsonObject.toString());
This will give you {"3" : "203", "2" : "200", "1": "100", "4": "4578"} as a string.
Not exactly sure why its not in the exact order, but sorting by a key is quite easy.
Related
I am getting response this
{
"success": 1,
"message": "some message",
"data": [
{
"comment_id": "43906",
"comp_id": "116725",
"user_id": "48322",
"agree": "0",
.....
"replies": [....]
},
{
"comment_id": "43905",
"comp_id": "116725",
"user_id": "48248",
"agree": "0",
.......
"replies": [...]
}
]
}
I am to get all response in json array like this
JSONObject js =new JSONObject(response);
routeJsonArray.=js.getJSONArray("data");
But I need to reverse all object which is inside data array .In other word when I get response and print commant_id "43906", "43905",
But I need I reverse that objects so that when I print it first give "43905","43906",
there is solution to iterate from i = routeJsonArray.length; i > 0; i-- But i don't want this.I want to store reverse array in another array ..
I try like this.
String [] routeStationString;
JSONArray localJsonArray = js.getJSONArray("data");
routeStationString = new String[localJsonArray.length()];
int k = 0;
for (int i = localJsonArray.length(); i > 0; i--) {
routeStationString[k++] = localJsonArray.getJSONObject(i);
}
System.out.println(routeStationString);
It gives error.?
My approach would be to create a Java Model representing a comment from your array and then proceed like this.
ArrayList<Comment> mList = new ArrayList<Comment>();
for(int i=0;i<routeJsonArray.length();i++){
//get the jsonobject based on the position
//retrieve its values
//create a new comment object and store it to the mList
}
Collection.reverse(mList);
You typically want to parse this array into a POJO, a model. So the idea would be to get a List<Comment> list for example and then you would be able to reverse that list through Collections.reverse(list) method.
How do you use the data from the JSON array? you still have to iterate it, plus remember the keys and everything. the most typical solution is to parse the JSON data into java objects.
JSONArray toReturn = new JSONArray();
int length = jsonArray.length()-1;
for(int i =length; i >= length;i--){
try {
toReturn.put(jsonArray.getJSONObject(i));
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(this, "Something wrong", Toast.LENGTH_SHORT).show();
}
}
Trying to parse multi-level JSON in Java.
Having JSON input in format like this:
{"object1":["0","1", ..., "n"],
"objects2":{
"x1":{"name":"y1","type":"z1","values":[19,20,21,22,23,24]}
"x2":{"name":"y2","type":"z2","values":[19,20,21,22,23,24]}
"x3":{"name":"y3","type":"z1","values":[19,20,21,22,23,24]}
"x4":{"name":"y4","type":"z2","values":[19,20,21,22,23,24]}
}
and need to get all objects from 2 by one of the attributes, e.g. get all objects with type = z1.
Using org.json*.
Tried to do something like this:
JSONObject GeneralSettings = new JSONObject(sb.toString()); //receiving and converting JSON;
JSONObject GeneralObjects = GeneralSettings.getJSONObject("objects2");
JSONObject p2;
JSONArray ObjectsAll = new JSONArray();
ObjectsAll = GeneralObjects.toJSONArray(GeneralObjects.names());
for (int i=0; i < GeneralObjects.length(); i++){
p2 = ObjectsAll.getJSONObject(i);
switch (p2.getString("type")) {
case "z1": NewJSONArray1.put(p2); //JSON array that should contain values with type z1.
break;
case "z2": NewJSONArray2.put(p2); //JSON array that should contain values with type z2.
default: System.out.println("error");
break;
}
}
}
But getting null pointer exception and overall method seems not to be so well.
Please advise, is there any way to make it easier or, what am I doing wrong?
If you're getting a NullPointerException it's most likely that you haven't initialized NewJSONArray1 and NewJSONArray2.
You didn't include their declaration, but you probably just need to do
NewJSONArray1=new JSONArray();
NewJSONArray2=new JSONArray();
before your loop.
Aside: by convention java variables should start with a lower case letter, e.g. newJSONArray1
public static void main(String[] args) {
String s =
"{\"object1\":[\"0\",\"1\",\"n\"]," +
"\"objects2\":{" +
"\"x1\":{\"name\":\"y1\",\"type\":\"z1\",\"values\":[19,20,21,22,23,24]}," +
"\"x2\":{\"name\":\"y2\",\"type\":\"z2\",\"values\":[19,20,21,22,23,24]}," +
"\"x3\":{\"name\":\"y3\",\"type\":\"z1\",\"values\":[19,20,21,22,23,24]}," +
"\"x4\":{\"name\":\"y4\",\"type\":\"z2\",\"values\":[19,20,21,22,23,24]}" +
"}}";
System.out.println(s);
JSONObject json = new JSONObject(s);
JSONObject object2 = json.optJSONObject("objects2");
if (object2 == null) {
return;
}
JSONArray result = new JSONArray();
for (Object key : object2.keySet()) {
JSONObject object = object2.getJSONObject(key.toString());
String type = object.optString("type");
if ("z1".equals(type)) {
System.out.println(object.toString());
result.put(object);
}
}
System.out.println(result);
}
You can always convert it to string and use json-path:
https://code.google.com/p/json-path/
I need a help... I have a php file which returns me two json Arrays which are as follows:
[{ "id":"1",
"item":"hammers",
"aisle":"20"
}
{ "id":"1",
"item":"hammers",
"aisle":"20"
}]
[{ "id":"1",
"itemFound":"Your item #item",
"ThankYou":"and Thank You for using Txtcore!"
}]
Now, I want to get the second array items in Android. I have the following code now which is like :
JSONArray jsonArray = new JSONArray(result);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
items.add(jsonObject.getString("item"));
aisles.add(""+jsonObject.getString("item");
}
But obviously, that returns me the objects from the first array. I want to get the Objects from the second array. Any suggestions.
Your JSON is not valid but u can get your element as follows. It is a solution from many(just a worlaround).
String str = "YOUR_JSON_RESPONSE";
String array[] = str.split("\\[\\{");//
try {
JSONArray jsonArray=new JSONArray("[{" + array[2]));
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
I guess you'll have to do some dirty coding because the data return by the PHP page is not well formed JSON.
You could try to transform the JSON data to:
{ "data" : [ <array_1>, <array_2> ]} And then use the JSON parser. A simple replacement with a regexp could be fine.
result.replaceAll("\\]\\s*\\[", "], [");
StringBuffer buffer=new StringBuffer(result);
buffer.insert(0,"{ \"data\": ");
buffer.append(" }");
JSONObject jsonObject = new JSONObject(buffer.toString());
JSONArray secondArray= jsonObject.getJSONArray("data").getJSONArray(1);
The creation of a valid JSON string can be done in one step with the appropriate regexp. Hope some one with more time can post it here.
How can I parse in Android a Json array of strings and save it in a java string array ( like: xy[ ] ) ?
My Json to be parsed :
[
{
"streets": [ "street1", "street2", "street3",... ],
}
]
Later in my code I want to populated with that array a spinner item in my layout.
Everything i tried enden with only one street item listed in the spinner.
To parse
try {
JSONArray jr = new JSONArray("Your json string");
JSONObject jb = (JSONObject)jr.getJSONObject(0);
JSONArray st = jb.getJSONArray("streets");
for(int i=0;i<st.length();i++)
{
String street = st.getString(i);
Log.i("..........",""+street);
// loop and add it to array or arraylist
}
}catch(Exception e)
{
e.printStackTrace();
}
Once you parse and add it to array. Use the same to populate your spinner.
[ represents json array node
{ represents json object node
Try this..
JSONArray arr = new JSONArray(json string);
for(int i = 0; i < arr.length(); i++){
JSONObject c = arr.getJSONObject(i);
JSONArray ar_in = c.getJSONArray("streets");
for(int j = 0; j < ar_in.length(); j++){
Log.v("result--", ar_in.getString(j));
}
}
We need to make JSON object first. For example,
JSONObject jsonObject = new JSONObject(resp);
// resp is your JSON string
JSONArray arr = jsonObject.getJSONArray("results");
Log.i(LOG, "arr length = " + arr.length());
for(int i=0;i<arr.length();i++)
{...
arr may contains other JSON Objects or JSON array. How to convert the JSON depends on the String. There is a complete example with some explanation about JSON String to JSON array can be found at http://www.hemelix.com/JSONHandling
Alright. I have a JSON Object sent to me from a server which contains the following data:
{
"result":
[
{"status":"green","type":"data1"},
{"status":"green","type":"data2"},
{"status":"green","type":"data3"}
],
"status":"ok"
}
The data I want to get is the status for the three status values. Data1, data2, and data3 always show up in that order, so I'm now trying to grab the data by index (e.g. data1 = index 0, data2 = index 1, data3 = index 2). How do I do that?
Try following:
String stat1;
String stat2;
String stat3;
JSONObject ret; //contains the original response
//Parse to get the value
try {
stat1 = ret.getJSONArray("results").getJSONObject(0).getString("status");
stat2 = ret.getJSONArray("results").getJSONObject(1).getString("status");
stat3 = ret.getJSONArray("results").getJSONObject(2).getString("status");
} catch (JSONException e1) {
e1.printStackTrace();
}
You would use JSONObject and JSONArray, the entire string is one JSONObject so you would construct one with it.
JSONObject object = new JSONObject(YOUR_STRING_OF_JSON);
Then you can access it with different get methods depending upon your expected type.
JSONArray results = object.getJSONArray("result"); // This is the node name.
String status = object.getString("status");
for (int i = 0; i < results.length(); i++) {
String resultStatus = results.getJSONObject(i).getString("status");
String type = results.getJSONObject(i).getString("type");
Log.w("JSON Result #" + i, "Status: " + resultStatus + " Type: " + type);
}
You need to surround it with a try/catch because JSON access can throw a JSONException.
Try re-factoring via a forEach loop
var testData =
{
"result":
[
{"status":"green","type":"data1"},
{"status":"green","type":"data2"},
{"status":"green","type":"data3"}
],
"status":"ok"
};
var output = new Object;
var resultSet = new Object;
resultSet = testData.result;
resultSet.forEach(function(data)
{
theStatus = data['status'];
theType = data['type']
output[theType] = theStatus;
});
console.log( output['data1'] );
If you've got your models setup to mirror that data set, then you can let GSON (https://code.google.com/p/google-gson/) do a lot of your work for you.
If you want a bit more control, and want to parse the set yourself you can use JSONObject, JSONArray. There's an example of parsing and assembling a json string here: Android create a JSON array of JSON Objects