First, create a class that represents a single json object, e.g.:
class MyObject {
private String image;
public MyObject(String name) { image = name; }
}
Gson will use the class' variable names to determine what property names to use.
Then create an array or list of these using the data you have available, e.g.
ArrayList<MyObject> allItems = new ArrayList<>();
allItems.add(new MyObject("name1"));
allItems.add(new MyObject("name2"));
allItems.add(new MyObject("name3"));
Finally, to serialize to Json, do:
String json = new Gson().toJson(allItems);
And to get the data back from json to an array:
MyObject[] items = new Gson().fromJson(json, MyObject[].class);
For simple (de)serialization, there is no need to be dealing directly with Json classes.
Answer from Allen G on Stack OverflowFirst, create a class that represents a single json object, e.g.:
class MyObject {
private String image;
public MyObject(String name) { image = name; }
}
Gson will use the class' variable names to determine what property names to use.
Then create an array or list of these using the data you have available, e.g.
ArrayList<MyObject> allItems = new ArrayList<>();
allItems.add(new MyObject("name1"));
allItems.add(new MyObject("name2"));
allItems.add(new MyObject("name3"));
Finally, to serialize to Json, do:
String json = new Gson().toJson(allItems);
And to get the data back from json to an array:
MyObject[] items = new Gson().fromJson(json, MyObject[].class);
For simple (de)serialization, there is no need to be dealing directly with Json classes.
If you are going to use GSON use it like this to convert to object
List<Image>images = new Gson().fromJson(json, Image[].class);
To get json string
String json = new Gson().toJson(images);
That's the point of gson you should not manipulate the data with loops and stuff. You need to take advantage of its powerful model parsing.
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;
}
}
the class:
public class JsonStructure{
public String[] message;
public String[] asec;
}
using it:
JsonStructure json = new JsonStructure();
json.message = new String[]{"msg 1", "msg 2", "msg 3"};
json.asec = new String[]{"asec 1", "asec 2", "asec 3"};
Gson gson = new Gson();
String output = gson.toJson(json);
//convert from string
JsonStructure fromString = gson.fromJson(output, JsonStructure.class);
For more details on Google's gson please take a look at https://sites.google.com/site/gson/gson-user-guide
public class ArrayBean {
ArrayList<String> message = new ArrayList<String>();
ArrayList<String> asec = new ArrayList<String>();
}
create bean class above arraybean, then u can add the values on your main class and print the output.
Gson gson = new Gson();
ArrayBean arrayBean = new ArrayBean();
arrayBean.message.add("msg 1");
arrayBean.message.add("msg 2");
arrayBean.message.add("msg 3");
arrayBean.asec.add("asec 1");
arrayBean.asec.add("asec 2");
arrayBean.asec.add("asec 3");
Log.d("rvg",""+gson.toJson(arrayBean));
You can get values using:
JsonObject propertiesJson = properties.get(0);
String value = propertiesJson.getString("value");
array is JsonArray object from com.google.gson library
for (int i=0; i<array.size(); i++) {
JsonObject json = array.get(i).getAsJsonObject();
String value = json.get("key").getAsString();
}
You can create a primitive that will contain the String value and add it to the array:
JsonArray jArray = new JsonArray();
JsonPrimitive element = new JsonPrimitive("value1");
jArray.add(element);
Seems like you should make a new JsonPrimitive("value1") and add that.
See The javadoc
hi if your json looks like this
{"status": "success",
"data": [
{
"trip_id": "5",
"ride_id": "5",
"start_location": "8 Rd No 14, Dhaka 1209, Bangladesh",
"end_location": "Uttara Dhaka, Dhaka Division, Bangladesh",
"date": "2017-03-14 17:36 PM",
"time_from": "1489491394079.5322 ",
"time_to": "1489493194079.5322 ",
"status": 5,
"trip_earn": "",
"currency": "CAD"
},
{
"trip_id": "5",
"ride_id": "5",
"start_location": "8 Rd No 14, Dhaka 1209, Bangladesh",
"end_location": "Uttara Dhaka, Dhaka Division, Bangladesh",
"date": "2017-03-14 17:36 PM",
"time_from": "1489491394079.5322 ",
"time_to": "1489493194079.5322 ",
"status": 5,
"trip_earn": "",
"currency": "CAD"
}
]
}
then your write a class like that for parsign the data
public class Example {
@SerializedName("status")
@Expose
private String status;
@SerializedName("data")
@Expose
private List<Datum> data = null;
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public List<Datum> getData() {
return data;
}
public void setData(List<Datum> data) {
this.data = data;
}
}
and
public class Datum {
@SerializedName("trip_id")
@Expose
private String tripId;
@SerializedName("ride_id")
@Expose
private String rideId;
@SerializedName("start_location")
@Expose
private String startLocation;
@SerializedName("end_location")
@Expose
private String endLocation;
@SerializedName("date")
@Expose
private String date;
@SerializedName("time_from")
@Expose
private String timeFrom;
@SerializedName("time_to")
@Expose
private String timeTo;
@SerializedName("status")
@Expose
private Integer status;
@SerializedName("trip_earn")
@Expose
private String tripEarn;
@SerializedName("currency")
@Expose
private String currency;
public String getTripId() {
return tripId;
}
public void setTripId(String tripId) {
this.tripId = tripId;
}
public String getRideId() {
return rideId;
}
public void setRideId(String rideId) {
this.rideId = rideId;
}
public String getStartLocation() {
return startLocation;
}
public void setStartLocation(String startLocation) {
this.startLocation = startLocation;
}
public String getEndLocation() {
return endLocation;
}
public void setEndLocation(String endLocation) {
this.endLocation = endLocation;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getTimeFrom() {
return timeFrom;
}
public void setTimeFrom(String timeFrom) {
this.timeFrom = timeFrom;
}
public String getTimeTo() {
return timeTo;
}
public void setTimeTo(String timeTo) {
this.timeTo = timeTo;
}
public Integer getStatus() {
return status;
}
public void setStatus(Integer status) {
this.status = status;
}
public String getTripEarn() {
return tripEarn;
}
public void setTripEarn(String tripEarn) {
this.tripEarn = tripEarn;
}
public String getCurrency() {
return currency;
}
public void setCurrency(String currency) {
this.currency = currency;
}
}
use like
Gson gson = new Gson();
String jsonInString = "{\"userId\":\"1\",\"userName\":\"chayon\"}";
Example user= gson.fromJson(jsonInString, Example.class);
user.getdata().get(position)
Create a Response POJO classes using jsonschema2pojo.
Add GSON dependency in your build.gradle
dependencies {
compile 'com.google.code.gson:gson:2.8.0'
}
Convert your json to specific pojo class as below:
Gson gson = new GsonBuilder().create();
Response response = gson.fromJson(response, Response.class);
Thanks!