import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
List<Contact> contacts;
Type listType = new TypeToken<List<Contact>>() {
}.getType();
contacts= new Gson().fromJson(jsonArray, listType);
This should work. make sure that your model class has same name as of json parameters and datatype. it will parse the jsonarray to type List of java
Answer from Sahil Manchanda on Stack Overflowimport com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
List<Contact> contacts;
Type listType = new TypeToken<List<Contact>>() {
}.getType();
contacts= new Gson().fromJson(jsonArray, listType);
This should work. make sure that your model class has same name as of json parameters and datatype. it will parse the jsonarray to type List of java
This already answered but i want to share one thing for you.Easy and best way
There is one plugin Gson for android studio.You need to install.Then go to CTRL + insert. You can create gson file. Enter some name for java file.
Click that file then Paste you json data. Click ok. You can see your created json to gson format.
thanks hope this will help you.
Actually you don't need the following line:
jsonObject.put("result", jsonArray);
Just use the existing jsonArray like the following:
String jsonResp = jsonArray.toString();
One other note. you will get extra " " in your response and that is because of jsonArray.put(i, string); statement in the for loop which inserts extra " ". you can simply use the following to fix that:
jsonResp = jsonResp.replaceAll("\"[{]", "{");
jsonResp = jsonResp.replaceAll("[}]\"", "}");
Make a Model like This DocInfoModel.java ->
public class DocInfoModel {
@SerializedName("doc_no")
@Expose
private String docNo;
@SerializedName("itembarcode")
@Expose
private String itembarcode;
@SerializedName("net_wt")
@Expose
private String netWt;
@SerializedName("gross_wt")
@Expose
private String grossWt;
@SerializedName("stone_amt")
@Expose
private String stoneAmt;
@SerializedName("rate")
@Expose
private String rate;
@SerializedName("making")
@Expose
private String making;
@SerializedName("qty")
@Expose
private String qty;
@SerializedName("net_rate")
@Expose
private String netRate;
@SerializedName("item_total")
@Expose
private String itemTotal;
@SerializedName("sum_total")
@Expose
private String sumTotal;
@SerializedName("stone_wt")
@Expose
private String stoneWt;
/**
*
* @return
* The docNo
*/
public String getDocNo() {
return docNo;
}
/**
*
* @param docNo
* The doc_no
*/
public void setDocNo(String docNo) {
this.docNo = docNo;
}
/**
*
* @return
* The itembarcode
*/
public String getItembarcode() {
return itembarcode;
}
/**
*
* @param itembarcode
* The itembarcode
*/
public void setItembarcode(String itembarcode) {
this.itembarcode = itembarcode;
}
/**
*
* @return
* The netWt
*/
public String getNetWt() {
return netWt;
}
/**
*
* @param netWt
* The net_wt
*/
public void setNetWt(String netWt) {
this.netWt = netWt;
}
/**
*
* @return
* The grossWt
*/
public String getGrossWt() {
return grossWt;
}
/**
*
* @param grossWt
* The gross_wt
*/
public void setGrossWt(String grossWt) {
this.grossWt = grossWt;
}
/**
*
* @return
* The stoneAmt
*/
public String getStoneAmt() {
return stoneAmt;
}
/**
*
* @param stoneAmt
* The stone_amt
*/
public void setStoneAmt(String stoneAmt) {
this.stoneAmt = stoneAmt;
}
/**
*
* @return
* The rate
*/
public String getRate() {
return rate;
}
/**
*
* @param rate
* The rate
*/
public void setRate(String rate) {
this.rate = rate;
}
/**
*
* @return
* The making
*/
public String getMaking() {
return making;
}
/**
*
* @param making
* The making
*/
public void setMaking(String making) {
this.making = making;
}
/**
*
* @return
* The qty
*/
public String getQty() {
return qty;
}
/**
*
* @param qty
* The qty
*/
public void setQty(String qty) {
this.qty = qty;
}
/**
*
* @return
* The netRate
*/
public String getNetRate() {
return netRate;
}
/**
*
* @param netRate
* The net_rate
*/
public void setNetRate(String netRate) {
this.netRate = netRate;
}
/**
*
* @return
* The itemTotal
*/
public String getItemTotal() {
return itemTotal;
}
/**
*
* @param itemTotal
* The item_total
*/
public void setItemTotal(String itemTotal) {
this.itemTotal = itemTotal;
}
/**
*
* @return
* The sumTotal
*/
public String getSumTotal() {
return sumTotal;
}
/**
*
* @param sumTotal
* The sum_total
*/
public void setSumTotal(String sumTotal) {
this.sumTotal = sumTotal;
}
/**
*
* @return
* The stoneWt
*/
public String getStoneWt() {
return stoneWt;
}
/**
*
* @param stoneWt
* The stone_wt
*/
public void setStoneWt(String stoneWt) {
this.stoneWt = stoneWt;
}
}
And Parse the json by GSON ->
Gson gson = new Gson();
DocInfoModel[] docModel = gson.fromJson(RESPONSE_STRING,DocInfoModel[].class);
You can parse the JSONArray directly, don't need to wrap your Post class with PostEntity one more time and don't need new JSONObject().toString() either:
Gson gson = new Gson();
String jsonOutput = "Your JSON String";
Type listType = new TypeToken<List<Post>>(){}.getType();
List<Post> posts = gson.fromJson(jsonOutput, listType);
I was looking for a way to parse object arrays in a more generic way; here is my contribution:
CollectionDeserializer.java:
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonParseException;
public class CollectionDeserializer implements JsonDeserializer<Collection<?>> {
@Override
public Collection<?> deserialize(JsonElement json, Type typeOfT,
JsonDeserializationContext context) throws JsonParseException {
Type realType = ((ParameterizedType)typeOfT).getActualTypeArguments()[0];
return parseAsArrayList(json, realType);
}
/**
* @param serializedData
* @param type
* @return
*/
@SuppressWarnings("unchecked")
public <T> ArrayList<T> parseAsArrayList(JsonElement json, T type) {
ArrayList<T> newArray = new ArrayList<T>();
Gson gson = new Gson();
JsonArray array= json.getAsJsonArray();
Iterator<JsonElement> iterator = array.iterator();
while(iterator.hasNext()){
JsonElement json2 = (JsonElement)iterator.next();
T object = (T) gson.fromJson(json2, (Class<?>)type);
newArray.add(object);
}
return newArray;
}
}
JSONParsingTest.java:
public class JSONParsingTest {
List<World> worlds;
@Test
public void grantThatDeserializerWorksAndParseObjectArrays(){
String worldAsString = "{\"worlds\": [" +
"{\"name\":\"name1\",\"id\":1}," +
"{\"name\":\"name2\",\"id\":2}," +
"{\"name\":\"name3\",\"id\":3}" +
"]}";
GsonBuilder builder = new GsonBuilder();
builder.registerTypeAdapter(Collection.class, new CollectionDeserializer());
Gson gson = builder.create();
Object decoded = gson.fromJson((String)worldAsString, JSONParsingTest.class);
assertNotNull(decoded);
assertTrue(JSONParsingTest.class.isInstance(decoded));
JSONParsingTest decodedObject = (JSONParsingTest)decoded;
assertEquals(3, decodedObject.worlds.size());
assertEquals((Long)2L, decodedObject.worlds.get(1).getId());
}
}
World.java:
public class World {
private String name;
private Long id;
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
}
String data = /*load the json data*/
try {
JSONArray jsonArray = new JSONArray(data);
JSONObject object = jsonArray.getJSONObject(0);
JSONObject sendingReqDataSetObject = object.getJSONObject("sendingReqDataSet");
JSONArray arrayContacts = sendingReqDataSetObject.getJSONArray("contacts");
for (int i = 0; i<arrayContacts.length(); i++) {
JSONObject contactObject = arrayContacts.getJSONObject(i);
System.out.println(contactObject.getString("status"));
}
} catch (JSONException e) {
e.printStackTrace();
}
You can get object by using following code :
jsonArray = jsonObject.getJSONArray("contacts");
for(int i=0; i<jsonArray.size(); i++) {
JSONObject jobject = jsonArray.getJSONObject(i)
}
Hope this part of code to help you:
String json = "{\"supplyPrice\": {\n" +
" \"CAD\": 78,\n" +
" \"CHF\": 54600.78,\n" +
" \"USD\": 20735.52\n" +
" }}";
Gson gson = new Gson();
JsonObject jsonObject = gson.fromJson(json, JsonObject.class);
JsonObject supplyPrice = jsonObject.get("supplyPrice").getAsJsonObject();
Type type = new TypeToken<HashMap<String, Double>>() {
}.getType();
HashMap<String, Double> parsedJson = gson.fromJson(supplyPrice, type);
JsonArray jsonArray = new JsonArray();
for(String key : parsedJson.keySet()) {
JsonObject jo = new JsonObject();
jo.addProperty("name", key);
jo.addProperty("value", parsedJson.get(key));
jsonArray.add(jo);
}
JsonObject result = new JsonObject();
result.add("supplyPrice", jsonArray.getAsJsonArray());
GSON uses POJO classes to parse JSON into java objects.
Create A java class containing variables with names and datatype same as keys of JSON object. I think the JSON you are getting is not in the right format.
Class SupplyPrice{
double CAD;
double CHF;
double TRY
}
Class SupplyPriceContainer{
ArrayList<SupplyPrice> supplyPrice;
}
And your JSON should be
{
"CAD": 78,
"CHF": 54600.78,
"USD": 20735.52
}
{
"supplyPrice": [{
"CAD": 78,
"CHF": 0,
"USD": 0
}, {
"CAD": 0,
"CHF": 54600.00,
"USD": 0
}, {
"CAD": 0,
"CHF": 0,
"USD": 20735.52
}]
}
Then you can Use GSON's `fromJson(String pJson, Class pClassType) to convert to JAVA object
Gson gson = new Gson()
ArrayList<SupplyPrice> suplyPrices = gson.fromJson(pJsonString, SupplyPrice.class);
Now you can use the arraylist to get the data.
use JsonParser; for example:
CopyJsonObject o = JsonParser.parseString("{\"a\": \"A\"}").getAsJsonObject();
Try to use getAsJsonObject() instead of a straight cast used in the accepted answer:
CopyJsonObject o = new JsonParser().parse("{\"a\": \"A\"}").getAsJsonObject();
There is a sample from google gson documentation on how to actually convert the list to json string:
CopyType listType = new TypeToken<List<String>>() {}.getType();
List<String> target = new LinkedList<String>();
target.add("blah");
Gson gson = new Gson();
String json = gson.toJson(target, listType);
List<String> target2 = gson.fromJson(json, listType);
You need to set the type of list in toJson method and pass the list object to convert it to json string or vice versa.
If response in your marshal method is a DataResponse, then that's what you should be serializing.
CopyGson gson = new Gson();
gson.toJson(response);
That will give you the JSON output you are looking for.
You can convert it to a JavaBean if you want using:
Gson gson = new GsonBuilder().setPrettyPrinting().create();
gson.fromJson(jsonString, JavaBean.class)
To use JsonObject, which is more flexible, use the following:
String json = "{\"Success\":true,\"Message\":\"Invalid access token.\"}";
JsonParser jsonParser = new JsonParser();
JsonObject jo = (JsonObject)jsonParser.parse(json);
Assert.assertNotNull(jo);
Assert.assertTrue(jo.get("Success").getAsString());
Which is equivalent to the following:
JsonElement jelem = gson.fromJson(json, JsonElement.class);
JsonObject jobj = jelem.getAsJsonObject();
To do it in a simpler way, consider below:
JsonObject jsonObject = (new JsonParser()).parse(json).getAsJsonObject();
Something like this:
JSONObject songs= json.getJSONObject("songs");
Iterator x = songs.keys();
JSONArray jsonArray = new JSONArray();
while (x.hasNext()){
String key = (String) x.next();
jsonArray.put(songs.get(key));
}
Even shorter and with json-functions:
JSONObject songsObject = json.getJSONObject("songs");
JSONArray songsArray = songsObject.toJSONArray(songsObject.names());