I have created 3 HashMaps all stored into an Arraylist but I cannot make it into a JSON String, I am using the GSON library.
Any help would kindly be appreciated.
Below you can see all the 3 hashmaps and the ArrayList x am adding them to.
private void createAdditionalPackages() {
if (chemoBtn.isChecked()) {
chemo.put("name", "chemo");
chemo.put("price", chemoButtonPrice);
}
if (cremBtn.isChecked()) {
cremation.put("name", "crematie");
cremation.put("price", cremationButtonPrice);
}
if (travenBtn.isChecked()) {
travel.put("name", "reisverz");
travel.put("price", travelButtonPrice);
}
x.add(chemo);
x.add(cremation);
x.add(travel);
List<JsonObject> jsonObjectList = new ArrayList<>() ;
for(HashMap<String, String> data : x){
JsonObject object = new JsonObject(data);
jsonObjectList.add(object);
}
JsonArray additional_coverages = new JsonArray(jsonObjectList);
See error :
JsonArray additional_coverages = new JsonArray();
// Iterate over your Hashmap
for (Map.Entry<String,String> data : x.entrySet()) {
// Create your JsonObject and use addProperty
JsonObject object = new JsonObject();
object.addProperty(data.getKey(), data.getValue());
// Add data in your JsonArray
additional_coverages.add(object);
}
You cannot directly add list of JsonObject to JsonArray
you can use something like this.
JsonArray additional_coverages = new JsonArray();
for(singleItem in jsonObjectList){
additional_coverages.put(singleItem )
}
I'm receiving a JSONObject like this
{"tag":"value1", "tag":"value2", .............}
How do I make it into a String array of
["value1", "value2"]
Create the Arraylist and get the string from the jsonobject and stored it in the arraylist.
Do like this
ArrayList tagarray=new ArrayList();
JSONObject jo=new JSONObject(jsonstring);
for(int i=0;i<jo.length();i++){
tagarray.add(jo.getString("tag"));
}
Try this way
JSONObject obj = new JSONObject("");
Iterator<String> itr = obj.keys();
int i=0;
String[] values = new String[obj.length()];
while(itr.hasNext()){
values[i++] = obj.getString((String)itr.next());
}
Use following code.
ArrayList array=new ArrayList();
JSONObject jo=new JSONObject(jsonstring);
for(int i=0;i<jo.length();i++){
array.add(jo.getString("tag"));
}
String[] Arr = new String[array.size()];
Arr = array.toArray(Arr);
Or you have another option.
JSONObject jo=new JSONObject(jsonstring);
String[] array = new String[jo.length()];
for(int i=0;i<jo.length();i++){
array[i] = jo.getString("tag");
}
There is super cool , lib called GSON , which is really helpfull for converting all type of JSON into its object .
If tags are going to be tag1, tag2 and so on...you can use a for loop,
string[i] = jsonObj.getString("tag"+i);
Or you can make a model class with datatype of String or ArrayList tag , eg.
class ModelClass{
ArrayList<String> tag;
//getter setter here
}
And with that use Gson for JSON parsing and mapping the data,
Gson gson = new Gson();
modelClass= gson.fromJson(yourJson,ModelClass.class);
And your work is done. You have each value in the ArrayList tag.
This is more useful for parsing and mapping long and-or complex json strings.
https://code.google.com/p/google-gson/
For Naming discrepancies(according to the variables in webservice), can use annotations like #SerializedName. (So no need to use Serializable)
I have a JSON Array like this:
[4, 3, 2, 1,...]
It is a simple array, and I am not able to find a single tutorial that tells me how to parse this array. I want to assign each element to a string Array that I have created like:
String H[];
I always get stuck when it comes to returning a value from a method, I get confused. For Example:
Within the Oncreate() method, after initializing all variables I type:
solarData();
//displaying only one value from the String Array H[];
TextView.setText(H[0]);
public JSONArray solarData() throws JSONException{
//After getting response from HttpClient and getting result
JSONArray jArray = new JSONArray(result);
for(int i=0;i<jArray,length();i++){
String H[i] = jArray.getJSONObject(i).toString();
}
return jArray;
}
Now what is it returning? I want it to return the String Array. So that I can display any value I want from the String Array to which I am storing these values.
From the JSONArray documentation, you can see there is a constructor that takes a valid JSON string and does all of the parsing work for you. You seem to have identified this already.
The problem here is that in each iteration of your for loop, you are attempting to create a new String array. You should initialize your array before the loop, and then populate its contents after initializing it. Something like this should work for you:
public JSONArray solarData() throws JSONException{
JSONArray jArray = new JSONArray(result);
// consider renaming H to something meaningful (e.g. planetList)
String H[] = new String[jArray.length()];
for (int i=0; i < jArray,length() ;i++) {
H[i] = jArray.getJSONObject(i).toString();
}
return jArray;
}
I'm developing an Android application that connects with Facebook using Springframework Android rest client.
With this URL:
https://graph.facebook.com/me/friends?access_token=AUTH_TOKEN
Facebook API returns:
{
"data": [
{
"name": "Friend1",
"id": "123456"
}
]
}
I want to parse the data[] values, as an array:
[
{
"name": "Friend1",
"id": "123456"
}
]
And get a FacebookFriend[].
How can I do it with GSON?
First, you'd need a FacebookFriend class (using public fields and no getters for simplicity):
public class FacebookFriend {
public String name;
public String id;
}
If you created a wrapper class such as:
public class JsonResponse {
public List<FacebookFriend> data;
}
Life becomes far simpler as you can simply do:
JsonResponse resp = new Gson().fromJson(myJsonString, JsonResponse.class);
And be done with it.
If you don't want to create an enclosing class with a data field, you'd use Gson to parse the JSON, then extract the array:
JsonParser p = new JsonParser();
JsonElement e = p.parse(myJsonString);
JsonObject obj = e.getAsJsonObject();
JsonArray ja = obj.get("data").getAsJsonArray();
(You can obviously chain all those methods, but I left them explicit for this demonstration)
Now you can use Gson to map directly to your class.
FacebookFriend[] friendArray = new Gson().fromJson(ja, FacebookFriend[].class);
That said, honestly it's better to use a Collection instead:
Type type = new TypeToken<Collection<FacebookFriend>>(){}.getType();
Collection<FacebookFriend> friendCollection = new Gson().fromJson(ja, type);
It seems, your array contain object.
you can parse it in following way.
JsonArray array = jsonObj.get("data").getAsJsonArray();
String[] friendList = new String[array.size()];
// or if you want JsonArray then
JsonArray friendArray = new JsonArray();
for(int i=0 ; i<array.size(); i++){
JsonObject obj = array.get(i).getAsJsonObject();
String name = obj.get("name").getAsString();
friendList[i] = name;
// or if you want JSONArray use it.
friendArray.add(new JsonPrimitive(name));
}
i want to analyse the json just like:
[{"id":"ssq","name":"双色球","term":"2010092","date":"2010-08-12 19:15","numbers":{"normal":"3,13,19,27,28,30","special":"2"},"jackpot":"30000000"},{"id":"3d","name":"3D","term":"2010216","date":"2010-08-12 19:55","numbers":{"normal":"6,8,8"},"jackpot":"-"},{"id":"qlc","name":"七乐彩","term":"2010093","date":"2010-08-11 20:45","numbers":{"normal":"08,09,10,11,16,21,27","special":"26"},"jackpot":"0"},{"id":"dfljy","name":"东方6+1","term":"2010093","date":"2010-08-14 18:30","numbers":{"normal":"4,1,3,9,7,2","special":"羊"},"jackpot":"12866531"},{"id":"swxw","name":"15选5","term":"2010217","date":"2010-08-12 18:45","numbers":{"normal":"1,3,5,13,15"},"jackpot":"5693612"},{"id":"ssl","name":"时时乐","term":"20100811-23","date":"2010-08-12 10:27","numbers":{"normal":"6,7,1"},"jackpot":"-"},{"id":"klsf","name":"快乐十分","term":"201021649","date":"2010-08-11 22:00","numbers":{"normal":"5,11,12,14,20"},"jackpot":"-"},{"id":"klsc","name":"快乐双彩","term":"2010215","date":"2010-08-10 21:25","numbers":{"normal":"12,23,10,15,7,3","special":"11"} ,"jackpot":"198059"}]
i want to gain all of them,but the data is so many,so whether i need to create 8 kinds of class to store the data,so to be easier to use.thanks!
To add to cfei's response, one thing that I've done when processing JSON responses from Flickr, is create a new class particularly for that type of object.
So for yours, just playing it by ear, something like the below:
public class Lottery() {
private JSONObject json;
private String id;
private String name;
private String term;
private String date;
private String norm_numbers;
private String spec_numbers;
private String jackpot;
public Lottery(JSONObject json) {
this.json = json;
}
public void setId()
{
try {
id = json.getString("id");
} catch (JSONException e) {
id = "";
}
}
//additional getters and setters, etc.
}
This way, you can make an array of objects, and access the fields like so:
//...get a JSONObject from the array...
Lottery lottery = new Lottery(json);
Log.v("ID", lottery.id);
Log.v("Name", lottery.name);
and so on.
Do you mean that you want to iterate through each of the eight JSONObjects in this JSONArray? You need to create a JSONArray object with the input string you posed above (let's call it "response", as used below) and then iterate through the array to get each JSONObject it contains. For example:
JSONArray array = new JSONArray(response);
for(int i = 0; i < array.length(); i++) {
JSONObject obj = array.getJSONObject(i);
// do something with obj
// example: to get the id for a particular object, use obj.getString("id")
Log.i("Example", "the id is"+obj.getString("id"));
}