Reputation: 247
I retrieve an Inventory object by making an HTTP GET using Volley:
JsonObjectRequest req = new JsonObjectRequest(Request.Method.GET,
Constants.API_URL + "inventory/lastInventoryWithLines/" + MyContext.User.getSiteId().toString(), null,
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
try {
Gson gson = new Gson();
inventory[0] = gson.fromJson(response.toString(), Inventory.class);
...
} catch (Exception e) {
Log.e("InventoryActivity", e.getMessage());
}
finally {
showProgress(false);
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
...
}
}
);
queue.add(req);
The important line is:
gson.fromJson(response.toString(), Inventory.class);
I've decorated my Inventory class with @SerializedName:
public class Inventory {
@SerializedName("InventoryId")
private UUID InventoryId;
@SerializedName("Title")
private String Title;
...
}
so this deserialization is easy.
Now, I want to update this Inventory object, and send it back to the server. Volley needs a JSONObject. So my question is: how could I convert my Inventory object to a JSONObject?
Upvotes: 1
Views: 7910
Reputation: 43206
In short, you have to do:
JsonObject jsonObject = gson.toJsonTree(myUpdatedInventory, Inventory.class).getAsJsonObject();
I didn't notice you weren't solely using google gson, so here is the updated answer, taken from another similar question:
new JSONObject(new Gson().toJson(inventory[0], Inventory.class));
Upvotes: 2