I need to convert a Vector<Vector<Float>> to a JSONArray. Apart from iterating through the vector and creating the JSONArray, is there any simpler way to do this?
Someone told me to try gson.
SharedPreferences is just a key-value store. What's stopping you from bypassing JSONObject completely, and just using something like this (Gson only)?
private static final Type DATA_TYPE =
new TypeToken<Vector<Vector<Float>>>() {}.getType();
Storage:
Vector<Vector<Float>> data = new Vector<Vector<Float>>();
data.add(new Vector<Float>());
data.get(0).add(3.0f);
String dataAsJson = new Gson().toJson(data, DATA_TYPE);
sharedPreferences.edit().putString("data", dataAsJson).commit();
Retrieval:
String dataAsJson = sharedPreferences.getString("data", "[]");
Vector<Vector<Float>> data = new Gson().fromJson(dataAsJson, DATA_TYPE);
Disclaimer: I've never developed for Android.
Related
I need to find a way of saving a HashMap to string to save in my SQLite database to retrieve on a later stage.
Here is my HashMap:
private Map<String, Bitmap> myMarkersHash new HashMap<String, Bitmap>();
Then when saving to the SQlite database:
contentValues.put(LocationsDB.FIELD_HASH, myMarkersHash);
But the problem is i get an error under put at contentValues.put with this error:
The method put(String, String) in the type ContentValues is not applicable for the arguments (String, Map<String,Bitmap>)
So my question is how can i convert that to a string so that i can save it into my sqlite database?
Thanks
You can store your HashMap in your Database by converting it into String using Gson library.
This library will convert your object to String and you will get back that object whenever you want it.
Link to Download Lib : https://code.google.com/p/google-gson/
Convert Object into String :
Gson objGson= new Gson();
String strObject = objGson.toJson(myMarkersHash);
Bundle bundle = new Bundle();
bundle.putString("key", strObject);
Convert String into Object :
Gson gson = new Gson();
Type type = new TypeToken<Model>() {}.getType();
myMarkersHash = gson.fromJson(bundle.getString("key"), type);
Check this example as well : http://www.java2blog.com/2013/11/gson-example-read-and-write-json.html
I need to parse json which I get from YQL but I am having trouble as I am not getting the results I need. I am using simple json (https://code.google.com/p/json-simple/wiki/DecodingExamples) and trying to follow the documentation. The problem is the example they show are very limited (I am very new to json). I want to extract everything in the array (Sy, Date, O, H, L, C, and V ). In the documentation they show how to extarct elements from an array if the json object is just as an array, but I have an array + some extra stuff on top:
{"query"
{"count":200,"created":"2014-06-17T00:46:43Z","lang":"en-GB","results"
This is the full json object, how would I extract just the array?
{"query"
{"count":200,"created":"2014-06-17T00:46:43Z","lang":"en-GB","results"
{"array":[{"Sy":"Y","Date":"2010-03-10","O":"16.51","H":"16.94","L":"16.51","C":"16.79","V":"33088600"},
{"Sy":"Y","Date":"2010-03-09","O":"16.41","H":"16.72","L":"16.40","C":"16.53","V":"20755200"},
{"Sy":"Y","Date":"2010-03-08","O":"16.32","H":"16.61","L":"16.30","C":"16.52","V":"30554000"}
]}}}
i use https://code.google.com/p/org-json-java/downloads/list
this is simple
try{
String json = "JSON source";
JSONObject j = new JSONObject(json);
JSONArray arr = j.getJSONObject("query").getJSONObject("results").getJSONArray("array");
for(int i=0; i<arr.length(); i++){
JSONObject obj = arr.getJSONObject(i);
String sy = obj.getString("Sy");
String date = obj.getString("Date");
String o = obj.getString("O");
String h = obj.getString("H");
String l = obj.getString("L");
String c = obj.getString("C");
String v = obj.getString("V");
}
}
catch(JSONException e){
}
You have to extract the array you need piece by piece.
JSONParser parser=new JSONParser();
String s="{YOUR_JSON_STRING}";
JSONArray array=parser.parse(s).get("query") //"query"
.get("result") // "query->result"
.get("array"); // THE array you need
Note that you might need to use try...catch... block to deal with exceptions.
Since you are using java, I highly recommend gson, which is written by google. It can convert json to object directly, which means you don't need to get the array deep inside the json step by step. https://code.google.com/p/google-gson/
Generally speaking, you can use gson to parse json piece by piece with jsonparser or, convert the whole json to a object with gson.
I'm using minimal-json (github) and am trying to create a nested JSON like so:
String jsonInner = new JsonObject().add("Inner", "i").toString();
String jsonMiddle = new JsonObject().add("Middle", jsonInner).toString();
String jsonOuter = new JsonObject().add("Outer", jsonMiddle).toString();
In my debug console, the result looks like this:
{"Outer":"{\"Middle\":\"{\\\"Inner\\\":\\\"i\\\"}\"}"}
Not quite what I was expecting; there is a bit much escaping going on...
I'm a bit slow today; can anyone please point out how to do this properly?
What about:
JsonValue inner = new JsonObject().add("Inner", "i");
JsonValue middle = new JsonObject().add("Middle", inner);
String outerAsString = new JsonObjec().add("Outer", middle).toString();
?
The problem is that you add a serialized JSON as a String in middle and outer; this is not what you want.
I've read through various threads and found similar problems, but have been pretty unsuccessful at finding a solution for my particular problem.
JSONObject orr = (JSONObject)orderRows.get("orderRows");
System.out.println("data in orr = " + orr + "orr's type = " + orr.getClass());
Returns:
data in orr =
{"470":[{"locationId":2,"quantity":1,"productId":1007}],"471":[{"locationId":2,"quantity":1,"productId":1008}]}orr's
type = class org.json.simple.JSONObject
I'm trying to get this data into an array/list/anything where I can use the keys, 470,471 to retrieve the data.
Any suggestions or pointers much appreciated many thanks...
To clarify:
JSONObject orr = (JSONObject)orderRows.get("orderRows");
JSONArray orderOne = (JSONArray)orr.get("471");
System.out.println(orderOne);
System.out.println(orderOne.get(0));
JSONObject orderOneKey = (JSONObject)orderOne.get(0);
System.out.println(orderOneKey.get("productId"));
This is what I'm after, but obviously I can't do orr.get("471") as I don't know what this number will be.
EDIT:
Apparently I can't answer my own question for 8 hours:
Thanks to help from a friend and some fiddling, I found a solution, I'm sure it's not the most eloquent, but it's exactly what I was after:
for(Object key: orr.keySet()) {
JSONArray orderOne = (JSONArray)orr.get(key);
JSONObject ordervalue = (JSONObject)orderOne.get(0);
System.out.println(ordervalue.get("productId"));
}
Thanks for the help and suggestions guys.
Thanks to help from a friend and some fiddling, I found a solution, I'm sure it's not the most eloquent, but it's exactly what I was after:
for(Object key: orr.keySet()) {
JSONArray orderOne = (JSONArray)orr.get(key);
JSONObject ordervalue = (JSONObject)orderOne.get(0);
System.out.println(ordervalue.get("productId"));
}
Thanks for the help and suggestions guys.
The data in your response is of type JSONObject (see the curly braces {}). So the top level object has two "fields", 470, and 471. Both of the data returned by these fields are arrays. Those arrays only have one item each, which are both objects. So here is an example of fetching the data:
JSONObject jsonObject = (JSONObject)orderRows.get("orderRows");
JSONArray firstArray = jsonObject.getJSONArray("470");
JSONArray secondArray = jsonObject.getJSONArray("471");
JSONObject firstObject = firstArray.get(0);
int locationId = firstObject.getId("locationId");
/*...etc...*/
Now once you've pulled it out you can transform this data into any structure you like to make it more friendly to access from this point forward.
You could use a library providing databinding support.
You can try Genson http://code.google.com/p/genson/, it is fast, easy to use and has a couple of nice features. Here is an example for your problem:
// first define a class matching your json
class Product {
private int locationId;
private int quantity;
private int productid;
// setter & getters
}
// then use genson
Map<String, Product[]> productsMap = new Genson().deserialize(jsonStream, new GenericType<Map<String, Product[]>>() {});
You can also do:
JSONArray jsonArr = new JSONArray();
jsonArr.put(jsonObj);
in the case where you want to put whole JSON object in JSON array.
I have problem when trying to parse with minimum value to map in Android.
There some sample JSON format with more information ex:
[{id:"1", name:"sql"},{id:"2",name:"android"},{id:"3",name:"mvc"}]
This that example most common to use and easy to use just use getString("id") or getValue("name").
But how do I parse to map using this JSON format with just only string and value minimum format to java map collection using looping. And because the string json will always different one with another. ex:
{"1":"sql", "2":"android", "3":"mvc"}
Thank
You need to get a list of all the keys, loop over them and add them to your map as shown in the example below:
String s = "{menu:{\"1\":\"sql\", \"2\":\"android\", \"3\":\"mvc\"}}";
JSONObject jObject = new JSONObject(s);
JSONObject menu = jObject.getJSONObject("menu");
Map<String,String> map = new HashMap<String,String>();
Iterator iter = menu.keys();
while(iter.hasNext()){
String key = (String)iter.next();
String value = menu.getString(key);
map.put(key,value);
}
My pseudocode example will be as follows:
JSONArray jsonArray = "[{id:\"1\", name:\"sql\"},{id:\"2\",name:\"android\"},{id:\"3\",name:\"mvc\"}]";
JSON newJson = new JSON();
for (each json in jsonArray) {
String id = json.get("id");
String name = json.get("name");
newJson.put(id, name);
}
return newJson;