I'm new to java so this is a bit confusing
I want to get json formatted string
The result I want is
{ "user": [ "name", "lamis" ] }
What I'm currently doing is this :
JSONObject json = new JSONObject();
json.put("name", "Lamis");
System.out.println(json.toString());
And I'm getting this result
{"name":"Lamis"}
I tried this but it didnt work
json.put("user", json.put("name", "Lamis"));
Try this:
JSONObject json = new JSONObject();
json.put("user", new JSONArray(new Object[] { "name", "Lamis"} ));
System.out.println(json.toString());
However the "wrong" result you showed would be a more natural mapping of "there's a user with the name "lamis" than the "correct" result.
Why do you think the "correct" result is better?
Another way of doing it is to use a JSONArray for presenting a list
JSONArray arr = new JSONArray();
arr.put("name");
arr.put("lamis");
JSONObject json = new JSONObject();
json.put("user", arr);
System.out.println(json); //{ "user": [ "name", "lamis" ] }
Probably what you are after is different than what you think you need;
You should have a separate 'User' object to hold all properties like name, age etc etc.
And then that object should have a method giving you the Json representation of the object...
You can check the code below;
import org.codehaus.jettison.json.JSONException;
import org.codehaus.jettison.json.JSONObject;
public class User {
String name;
Integer age;
public User(String name, Integer age) {
this.name = name;
this.age = age;
}
public JSONObject toJson() {
try {
JSONObject json = new JSONObject();
json.put("name", name);
json.put("age", age);
return json;
} catch (JSONException e) {
e.printStackTrace();
return null;
}
}
public static void main(String[] args) {
User lamis = new User("lamis", 23);
System.out.println(lamis.toJson());
}
}
Related
The problem I am facing is that I want to ser/des null values when only it comes to non top-level attributes, and I have no idea how to achieve that. So let's say I have a User class:
Class User {
String name;
int id;
Address address;
}
And an Address class:
Class Address{
String street;
String city;
String country;
}
Right now, I can use below Gson instance to ser/des null values:
Gson gson = new GsonBuilder().serializeNulls().create();
Address address = new Address(null, "New York", "US");
User user = new User("Adam", 123, address);
String userJson = gson.toJson(user);
Output is:
{
"name": "Adam",
"id": 123,
"address": {
"street": null,
"city": "New York",
"country": "US"
}
}
However, I do NOT want to ser/des nulls when it comes to top-level attributes of User. For example for below User:
User user = new User("Adam", 123, null);
I want to have an output as below and without address field:
{
"name": "Adam",
"id": 123
}
I am now trying to use a customized serializer to hardcode every top-level attributes and remove them if they are null:
public class SerializerForUser implements JsonSerializer<ConfigSnapshot> {
#Override
public JsonElement serialize(User user, Type type, JsonSerializationContext jsc) {
Gson gson = new GsonBuilder().serializeNulls().create();
JsonObject jsonObject = gson.toJsonTree(user).getAsJsonObject();
if (user.getAddress() == null) {
jsonObject.remove("address");
}
// if... (same with other top-level attributes)
return jsonObject;
}
}
Gson gson = new GsonBuilder().serializeNulls().registerTypeAdapter(User.class, new SerializerForUser()).create();
But somehow it is not working, I will still get below output when for example address is null:
{
"name": "Adam",
"id": 123,
"address: null
}
can anyone give me some hints on what did I wrong here? Or it would be perfect if anyone can tell me if there is more straight forward/general way to achieve this(since I also want to use the same gson instance to ser/des other objects)?
Any comments are appreciated.
Because you are using
Gson gson = new GsonBuilder().serializeNulls().create();
which shows null value.
To skip showing null, let's try
Gson gson = new Gson();
You can test here
public static void main(String[] args) {
Gson yourGson = new GsonBuilder().serializeNulls().create(); // this is how you create your Gson object, which shows null value
Address address = new Address(null, "New York", "US");
User user = new User("Adam", 123, address);
String userJson = yourGson.toJson(user);
System.out.println(userJson);
Gson newGson = new Gson(); // with this one, it doesn't show value
System.out.println(newGson.toJson(user));
}
Update
I have tried to override the method serialize with a few times and it failed until I try #5
public class UserCustomSerializer implements JsonSerializer<User> {
#Override
public JsonElement serialize(User src, Type typeOfSrc, JsonSerializationContext context) {
JsonObject obj = new JsonObject();
if (src.name != null) {
obj.addProperty("name", src.name);
}
obj.addProperty("id", src.id);
if (src.address != null) {
// try #1
//JsonObject addressJsonObj = new JsonObject();
//addressJsonObj.addProperty("street", src.address.street != null ? src.address.street : null);
//addressJsonObj.addProperty("city", src.address.city != null ? src.address.city : null);
//addressJsonObj.addProperty("country", src.address.country != null ? src.address.country : null);
//obj.add("address", addressJsonObj);
// try #2
//Gson gson = new GsonBuilder().serializeNulls().create();
//JsonElement jsonElement = gson.toJsonTree(src.address);
//obj.add("address", jsonElement);
// try #3
//Gson gson2 = new GsonBuilder().serializeNulls().create();
//obj.addProperty("address", gson2.toJson(src.address));
// try #4
//Gson gson = new GsonBuilder().serializeNulls().create();
//JsonObject jsonObject = gson.toJsonTree(src.address).getAsJsonObject();
//obj.add("address", jsonObject);
// try #5
JsonObject addressJsonObj = new JsonObject();
addressJsonObj.addProperty("street", src.address.street != null ? src.address.street : "null");
addressJsonObj.addProperty("city", src.address.city != null ? src.address.city : "null");
addressJsonObj.addProperty("country", src.address.country != null ? src.address.country : "null");
obj.add("address", addressJsonObj);
}
return obj;
}
}
For try #3, I built the incorrect String.
For try #1, #2 and #4, I have the problem with the null value. I searched and found the reason and also the suggestion here
In a JSON "object" (aka dictionary), there are two ways to represent absent values: Either have no key/value pair at all, or have a key with the JSON value null.
So you either use .add with a proper value what will get translated to null when you build the JSON, or you don't have the .add call.
And my #5 approach is to check if the child node is null, I just add the string "null" literally and then I replace it when I build the json string
private String parseToGson(User user){
Gson gson = new GsonBuilder().registerTypeAdapter(User.class, new UserCustomSerializer()).create();
return gson.toJson(user).replace("\"null\"", "null");
}
Here are some test cases I defined
#Test
public void children_attribute_is_null() throws Exception {
String expected = "{\"name\":\"Adam\","
+ "\"id\":123,"
+ "\"address\":{"
+ "\""+ "street\":null,"
+ "\"city\":\"New York\","
+ "\"country\":\"US"
+ "\"}"
+ "}";
Address address = new Address(null, "New York", "US");
User user = new User("Adam", 123, address);
assertEquals(expected, parseToGson(user));
Gson g = new Gson();
User usr = g.fromJson( parseToGson(user), User.class);
assertEquals("Adam", usr.name);
assertEquals(123, usr.id);
assertEquals(null, usr.address.street);
assertEquals("New York", usr.address.city);
assertEquals("US", usr.address.country);
}
#Test
public void parent_attribute_is_null() throws Exception {
String expected = "{\"name\":\"Adam\","
+ "\"id\":123" + "}";
User user = new User("Adam", 123, null);
assertEquals(expected, parseToGson(user));
Gson g = new Gson();
User usr = g.fromJson( parseToGson(user), User.class);
assertEquals("Adam", usr.name);
assertEquals(123, usr.id);
assertEquals(null, usr.address);
}
#Test
public void parent_attribute_and_children_attribute_are_null() throws Exception {
String expected = "{\"id\":123,"
+ "\"address\":{"
+ "\"street\":null,"
+ "\"city\":\"New York\","
+ "\"country\":\"US"
+ "\"}"
+ "}";
Address address = new Address(null, "New York", "US");
User user = new User(null, 123, address);
assertEquals(expected, parseToGson(user));
Gson g = new Gson();
User usr = g.fromJson( parseToGson(user), User.class);
assertEquals(null, usr.name);
assertEquals(123, usr.id);
assertEquals(null, usr.address.street);
assertEquals("New York", usr.address.city);
assertEquals("US", usr.address.country);
}
Update #2
Since the previous version is not a generic one, I would like to update the answer.
For generic, I created MyCustomSerializer as following
public class MyCustomSerializer<T> implements JsonSerializer<T> {
private final Class<T> type;
public MyCustomSerializer(Class<T> type) {
this.type = type;
}
public Class<T> getMyType() {
return this.type;
}
#Override
public JsonElement serialize(T src, Type typeOfSrc, JsonSerializationContext context) {
JsonObject obj = new JsonObject();
try {
Field[] declaredFields = this.type.getDeclaredFields();
for (Field field : declaredFields) {
Object object = field.get(src);
if (object != null) {
// Here, we check for 4 types of JsonObject.addProperty
if (object instanceof String) {
obj.addProperty(field.getName(), (String) object);
continue;
}
if (object instanceof Number) {
obj.addProperty(field.getName(), (Number) object);
continue;
}
if (object instanceof Boolean) {
obj.addProperty(field.getName(), (Boolean) object);
continue;
}
if (object instanceof Character) {
obj.addProperty(field.getName(), (Character) object);
continue;
}
// This is where we check for other types
// The idea is if it is an object, we need to care its child object as well, so parse it into json string and replace the null value.
Gson gson = new GsonBuilder().serializeNulls().create();
String json = gson.toJson(object);
json = json.replace("null", "\"null\""); // We have to build the string first, then replace it with our special keys. In this case, I use the string "null"
JsonObject convertedObject = new Gson().fromJson(json, JsonObject.class); // Then convert it back to json object
obj.add(field.getName(), convertedObject);
}
}
} catch (IllegalAccessException e) {
e.printStackTrace();
}
return obj;
}
}
The main idea is still the same as previous version but I made it to a generic one.
I also added some additional properties to test for the string this code builds with the results
{
"id":123,
"address":{
"street":null,
"city":"New York",
"country":"US",
"info":{
"zipcode":null,
"address2":"stackoverflow",
"workPlaceAddress":{
"street":null,
"companyName":"google"
}
}
}
}
To call this, we need to do
private String parseToGson(User user) {
Gson gson = new GsonBuilder().registerTypeAdapter(User.class, new MyCustomSerializer<>(User.class)).create();
return gson.toJson(user).replace("\"null\"", "null");
}
Update #3
Since you still concern about your solution, I tried to adapt it as well
public class YourSerializer <T> implements JsonSerializer<T>{
private final Class<T> type;
public YourSerializer(Class<T> type) {
this.type = type;
}
public Class<T> getMyType() {
return this.type;
}
#Override
public JsonElement serialize(T src, Type typeOfSrc, JsonSerializationContext context) {
Gson gson = new GsonBuilder().serializeNulls().create();
JsonObject jsonObject = gson.toJsonTree(src).getAsJsonObject();
Field[] declaredFields = this.type.getDeclaredFields();
for (Field field : declaredFields) {
try {
if(field.get(src) == null) {
jsonObject.remove(field.getName());
}
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
return jsonObject;
}
}
The reason is you used serializeNulls() incorrectly which makes your output is incorrect. To correct it, you should registerTypeAdapter first to create your custom json, then you call serializeNulls
private String parseToGson(User user) {
Gson gson = new GsonBuilder().registerTypeAdapter(User.class, new YourSerializer<>(User.class)).serializeNulls().create();
return gson.toJson(user);
}
I tested and got the same result with update#2
{
"id":123,
"address":{
"street":null,
"city":"New York",
"country":"US",
"info":{
"zipcode":null,
"address2":"aaa",
"workPlaceAddress":{
"street":null,
"companyName":"google"
}
}
}
}
Im learning how to produce and consume JSON in rest services, but I wanna learn it well so im trying all possible cases of objects, one of them is an object that has an List attribute like this class:
import java.util.List;
public class PruebaJSON {
private String nombre;
private List atributos;
private String descripcion;
public String getNombre() {
return nombre;
}
public void setNombre(String nombre) {
this.nombre = nombre;
}
public List getAtributos() {
return atributos;
}
public void setAtributos(List atributos) {
this.atributos = atributos;
}
public String getDescripcion() {
return descripcion;
}
public void setDescripcion(String descripcion) {
this.descripcion = descripcion;
}
}
Then all what im doing on my rest service method is this:
#POST
#Path("/prueba")
#Consumes(MediaType.APPLICATION_JSON)
#Produces(MediaType.APPLICATION_JSON)
public PruebaJSON prueba(String data) {
try {
JSONObject json = new JSONObject(data);
Gson convertir = new GsonBuilder().create();
PruebaJSON pruebaJson = convertir.fromJson(json.toString(), PruebaJSON.class);
return pruebaJson;
} catch (Exception e) {
System.out.println("error " + e);
return null;
}
}
Then in POSTMAN I pass this:
{
"descripcion": "Primera prueba",
"nombre": "Prueba 1",
"atributos": [
"hello",
"kek",
"lul"
]
}
And it works fine, the problem is when I try to do the same by Java, for example:
List atributos = new ArrayList<>();
atributos.add("hello");
atributos.add("kek");
atributos.add("lul");
System.out.println(bus.prueba("Prueba 1", "Primera Prueba", atributos));
bus.prueba just executes the service but then in console I get this error:
14:16:56,567 INFO [stdout] (default task-2) error com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_ARRAY but was STRING at line 1 column 66 path $.atributos
I did the search of the error and found this:
Gson: Expected begin_array but was STRING
I understand the error but whats the solution?
I can't really control how the JSON builds the arraylist can I?
This is the method prueba in my client:
public String prueba(String nombre, String descripcion, List atributos) {
HashMap map = new HashMap<>();
map.put("nombre", nombre);
map.put("descripcion", descripcion);
map.put("atributos", atributos);
String respuesta = utilidadesRestSeguridad.consumir("prueba", map);
return respuesta;
}
In my client component this is the method that builds the json:
public static JsonObject generateJSON(HashMap map) throws MalformedURLException {
JsonObject json = new JsonObject();
for (Object key : map.keySet()) {
json.addProperty(key.toString(), map.get(key).toString());
}
return json;
}
And thats it guys if you wanna see more code or me to explain something tell me I appreciate any help.
I think maybe the error is in the method generateJSON because of the .toString(), but then how I should handle that case?
Assuming that the line utilidadesRestSeguridad.consumir("prueba", map) ends up calling your generateJSON method downstream, then your issue is likely in the generateJSON() method as you suspect. Basically, you are just adding all elements as strings. If one of the elements in your map is an instance of a List, then you need to call JsonObject#add("atributos", value). For example, you will need something like the following code:
if (map.get(key) instanceof List) {
json.add(key.toString(), map.get(key);
} else {
json.addProperty(key.toString(), map.get(key).toString());
}
As I suspected, the error was in the generateJSON method, needed to add this validation that entpnerd suggested:
public static JsonObject generateJSON(HashMap map) throws MalformedURLException {
JsonObject json = new JsonObject();
for (Object key : map.keySet()) {
if (map.get(key) instanceof List) {
JsonParser parser = new JsonParser();
parser.parse((map.get(key).toString()));
json.add(key.toString(), parser.parse((map.get(key).toString())));
} else {
json.addProperty(key.toString(), map.get(key).toString());
}
}
return json;
}
Notice that I had to use JsonParser, not sure how is it working but at the end that made it work.
Source: How to parse this JSON String with GSON?
Anyways Im gonna try the solution entpnerd is suggesting and post it too.
Here is the implementation of entpnerd suggestion:
public static JsonObject generateJSON(HashMap map) throws MalformedURLException {
JsonObject json = new JsonObject();
for (Object key : map.keySet()) {
if (map.get(key) instanceof List) {
JsonArray jsonArray = new JsonArray();
for (Object object : (ArrayList<Object>) map.get(key)) {
jsonArray.add(object.toString());
}
json.add(key.toString(), jsonArray);
} else {
json.addProperty(key.toString(), map.get(key).toString());
}
}
return json;
}
it works too, you guys decide which one to use, thanks very much.
My only question is, what if the element that is an array, has more arrays inside it, what would you do?
You don't need to get that json value manually, add requestbody annotation to your method parameter
public PruebaJSON prueba(#RequestBody PruebaJSON json){
System.out.println(json);
};
This is the JSON array:
{
"server_response": [{
"Total": "135",
"Paid": "105",
"Rest": "30"
}]
}
So, how can i get the object names? I want to put them in separate TextView.
Thanks.
Put this out side everything. I mean outside onCreate() and all.
private <T> Iterable<T> iterate(final Iterator<T> i){
return new Iterable<T>() {
#Override
public Iterator<T> iterator() {
return i;
}
};
}
For getting the names of objects :
try
{
JSONObject jsonObject = new JSONObject("{" +"\"server_response\": [{" +"\"Total\": \"135\"," +"\"Paid\": \"105\"," +"\"Rest\": \"30\"" +"}]"+"}";);
JSONArray jsonArray = jsonObject.getJSONArray("server_response");
JSONObject object = jsonArray.getJSONObject(0);
for (String key : iterate(object.keys()))
{
// here key will be containing your OBJECT NAME YOU CAN SET IT IN TEXTVIEW.
Toast.makeText(HomeActivity.this, ""+key, Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
Hope this helps :)
My suggestion:
Go to this website:
Json to pojo
Get your pojo classes and then use them in Android.
All you need to do is to use Gson.fromGson(params here).
One of your params is the class that you created using the online schema.
You can use jackson ObjectMapper to do this.
public class ServerResponse {
#JsonProperty("Total")
private String total;
#JsonProperty("Paid")
private String paid;
#JsonProperty("Rest")
private String rest;
//getters and setters
//toString()
}
//Now convert json into ServerResponse object
ObjectMapper mapper = new ObjectMapper();
TypeReference<ServerResponse> serverResponse = new TypeReference<ServerResponse>() { };
Object object = mapper.readValue(jsonString, serverResponse);
if (object instanceof ServerResponse) {
return (ServerResponse) object;
}
JSONObject jsonObject = new JSONObject("Your JSON");
int Total = jsonObject.getJSONArray("server_response").getJSONObject(0).getInt("Total");
int Paid = jsonObject.getJSONArray("server_response").getJSONObject(0).getInt("Paid");
int Rest = jsonObject.getJSONArray("server_response").getJSONObject(0).getInt("Rest");
Hi i am trying to iterate through a json string that looks like this:
{
"vendor":[
{
"vendor_name":"Tapan Moharana",
"vendor_description":"",
"vendor_slug":"tapan",
"vendor_logo":null,
"contact_number":null
}
],
"products":
{
"25":
{
"name":"Massage",
"price":"5000.0000",
"image":"http:\/\/carrottech.com\/lcart\/media\/catalog\/product\/cache\/1\/image\/150x\/9df78eab33525d08d6e5fb8d27136e95\/2\/9\/29660571-beauty-spa-woman-portrait-beautiful-girl-touching-her-face.jpg"
},
"26":
{
"name":"Chicken Chilly",
"price":"234.0000",
"image":"http:\/\/carrottech.com\/lcart\/media\/catalog\/product\/cache\/1\/image\/150x\/9df78eab33525d08d6e5fb8d27136e95\/c\/h\/cheicken.jpg"
},
"27":
{
"name":"Chicken Biryani",
"price":"500.0000",
"image":"http:\/\/carrottech.com\/lcart\/media\/catalog\/product\/cache\/1\/image\/150x\/9df78eab33525d08d6e5fb8d27136e95\/placeholder\/default\/image_1.jpg"
}
}
}
here is a better view of the json string:
I am iterating through the vendor array of this json string using this code:
JSONObject jsono = new JSONObject(response);
JSONArray children = jsono.getJSONArray("vendor");
for (int i = 0; i <children.length(); i++) {
JSONObject jsonData = children.getJSONObject(i);
System.out.print(jsonData.getString("vendor_name") + "<----");
// String vendorThumbNailURL=jsonData.getString("")
//jvendorImageURL.setImageUrl(local, mImageLoader);
vendorLogo=vendorLogo+jsonData.getString("vendor_logo").trim();
jvendorImageURL.setImageUrl(vendorLogo, mImageLoader);
jvendorName.setText(jsonData.getString("vendor_name"));
jvendorAbout.setText(jsonData.getString("vendor_description"));
jvendorContact.setText(jsonData.getString("contact_number"));
}
but I dont know how to get data from the "products" object please help me how do i set my json objects to iterate through "products"
when i try to change the format of the array so that both products and vendor are a separate json array i still get the above json format..
this is what i am doing
$resp_array['vendor'] = $info;
$resp_array['products'] = $vendorProductsInfo;
$resp_array = json_encode($resp_array);
print_r($resp_array);
please help me with this
MODIFIED QUESTION:
I have modified my web response like this:
[{"entity_id":24,"product_name":"Burger","product_image_url":"\/b\/u\/burger_large.jpg","price":"234.0000","category_id":59},{"entity_id":27,"product_name":"Chicken Biryani","product_image_url":"\/b\/i\/biryani.jpg","price":"500.0000","category_id":59},{"entity_id":31,"product_name":"Pizza","product_image_url":"\/p\/i\/pizza_png7143_1.png","price":"125.0000","category_id":59}]
and the code:
JSONArray children = jsono.getJSONArray("vendor");
for (int i = 0; i <children.length(); i++) {
JSONObject jsonData = children.getJSONObject(i);
System.out.print(jsonData.getString("vendor_name") + "<----");
// String vendorThumbNailURL=jsonData.getString("")
//jvendorImageURL.setImageUrl(local, mImageLoader);
vendorLogo=vendorLogo+jsonData.getString("vendor_logo").trim();
jvendorImageURL.setImageUrl(vendorLogo, mImageLoader);
jvendorName.setText(jsonData.getString("vendor_name"));
jvendorAbout.setText(jsonData.getString("vendor_description"));
jvendorContact.setText(jsonData.getString("contact_number"));
System.out.print(jsonData.getString("products") + "<----");
}
JSONObject jsono1 = new JSONObject(response);
JSONArray childrenProducts = jsono1.getJSONArray("products");
for(int i=0;i<childrenProducts.length();i++){
JSONObject jsonData = childrenProducts.getJSONObject(i);
System.out.print(jsonData.getString("name") + "<----dd");
}
but still the products part is not working... please help
Here is the working solution: Using GOOGLE GSON (Open source jar)
import java.io.IOException;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
public class JsonToJava {
public static void main(String[] args) throws IOException {
try{
String json = "<YOUR_JSON>";
Gson gson = new GsonBuilder().create();
VendorInfo vInfo = gson.fromJson(json, VendorInfo.class);
System.out.println(vInfo.getVendorName());
} catch(Exception ex) {
ex.printStackTrace();
}
}
}
Create classes for Vendor and Product
public class Vendor {
public String vendor_name;
public String vendor_description;
public String vendor_slug;
public String vendor_logo;
public String contact_number;
public String getName() {
return vendor_name;
}
}
public class Product {
public String name;
public long price;
public String image;
public String getName() {
return name;
}
}
VendorInfo is the JSON object form:
import java.util.Map;
public class VendorInfo {
public Vendor[] vendor;
public Map<Integer, Product> products;
public String getVendorName() {
return vendor[0].getName();
}
public Product getProduct() {
System.out.println(products.size());
return products.get(25);
}
}
You can add your getters for Vendor, Product and VendorInfo. You are done! You will get all the data.
Output of JsonToJava:
Tapan Moharana
To get your products data , you need to use Iterator
JSONObject jProducts = jsonObject
.optJSONObject("products");
try {
if (jProducts
.length() > 0) {
Iterator<String> p_keys = jProducts
.keys();
while (p_keys
.hasNext()) {
String keyProduct = p_keys
.next();
JSONObject jP = jProducts
.optJSONObject(keyProduct);
if (jP != null) {
Log.e("Products",
jP.toString());
}
}
}
} catch (Exception e) { // TODO:
// handle
// exception
}
you can try with this
JSONObject jsono = null;
try {
jsono = new JSONObject(response);
JSONObject productObject = jsono.getJSONObject("products");
Iterator<String> keys = productObject.keys();
while (keys.hasNext())
{
// get the key
String key = keys.next();
// get the value
JSONObject value = productObject.getJSONObject(key);
//get seprate objects
String name = value.getString("name");
String image = value.getString("image");
Log.i(TAG,name+"-"+image);
}
}
catch (JSONException e) {
e.printStackTrace();
}
Try this :
JSONObject productObject = jsono.getJSONObject("products");
JSONObject json_25 = productObject getJSONObject("25");
String name_25= json_25.getString("name");
String price_25= json_25.getString("price");
String image_25= json_25.getString("image");
JSONObject json_26 = productObject getJSONObject("26");
String name_26= json_26.getString("name");
String price_26= json_26.getString("price");
String image_26= json_26.getString("image");
JSONObject json_27 = productObject getJSONObject("27");
String name_27= json_27.getString("name");
String price_27= json_27.getString("price");
String image_27= json_27.getString("image");
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions must demonstrate a minimal understanding of the problem being solved. Tell us what you've tried to do, why it didn't work, and how it should work. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
A have a hard string from Json. Example:
[
{
"Group1": [
{
"id": "2b3b0db",
"name": "Ivan"
},
{
"id": "4f3b0db",
"name": "Lera"
}
]
},
{
"Group2": [
{
"id": "42ae2a7",
"name": "Victor"
}
]
}
]
How i can parse it from Gson? Thanks!
This link describes json to java and java to json using Gson
http://www.mkyong.com/java/how-do-convert-java-object-to-from-json-format-gson-api/
Json to Java using GSON
Gson gson = new Gson();
try {
BufferedReader br = new StringReader(<CONTENT>);
//convert the json string back to object
// In your case this is Group object
Object obj = gson.fromJson(br, Object .class);
System.out.println(obj);
} catch (IOException e) {
e.printStackTrace();
}
Java Object to json String using GSON
Object obj = new Object();
Gson gson = new Gson();
// convert java object to JSON format,
// and returned as JSON formatted string
String json = gson.toJson(obj);
In your case use this :
public static void main(final String[] args) {
String Group1 = " [ { \"id\": \"2b3b0db\", \"name\": \"Ivan\" }, { \"id\": \"4f3b0db\", \"name\": \"Lera\" } ] ";
Gson gson = new Gson();
Group[] object = gson.fromJson(new StringReader(Group1), Group[].class);
System.out.println(object);
}
public class Group {
private String id;
private String name;
public String getId() {
return id;
}
public String getName() {
return name;
}
public void setName(final String name) {
this.name = name;
}
public void setId(final String id) {
this.id = id;
}
}
try following code
public String parse(String jsonLine)
{
JSONArray jArraymain=new JSONArray(jsonLine);
JSONObject jobject=array.getJSONObject(0);
JSONArray jArraySub=jobject.getJSONArray("Group1");
for(int i=0;i<=jobject.length;i++)
{
String temp=jArraySub.get(i).toString();
}
}
also you can use this
public String parse(String jsonLine) {
JsonElement jelement = new JsonParser().parse(jsonLine);
JsonObject jobject = jelement.getAsJsonObject();
jobject = jobject.getAsJsonObject("data");
JsonArray jarray = jobject.getAsJsonArray("translations");
jobject = jarray.get(0).getAsJsonObject();
String result = jobject.get("translatedText").toString();
return result;
}
Below will help you. I havnt executed the below code snippet yet.
JsonElement jelement = new JsonParser().parse("json data");
JsonArray jgrouparray = jelement.getAsJsonArray();
for(int i=0; i<jgrouparray.size(); i++){
JsonArray jgroup = jgrouparray.get(i).getAsJsonArray("Group"+i);
for(int j=0; j<jgroup.size(); j++){
JsonObject jobject = jgroup.get(j).getAsJsonObject();
String id = jobject.get("id").toString();
String name = jobject.get("name").toString();
}
}
For more info look into: JSON parsing using Gson for Java
Do you have to use GSON? If you can use JSONObject from json.org you can almost get it:
URL url = this.getClass().getClassLoader().getResource("json" + File.separator + "GroupJson.json");
JSONArray jsonArray = new JSONArray(FileUtil.readFile(url.getPath()));
JSONObject jsonObject = jsonArray.getJSONObject(0);
log.info("{}", jsonObject.toString());
this outputs: {"Group1":[{"id":"2b3b0db","name":"Ivan"},{"id":"4f3b0db","name":"Lera"}]}