Showing posts with label JSON. Show all posts

Google Gson for converting Java object to / from JSON

Following code snippet shows how you can convert Java object to JSON string and vice versa.

Source code (Item.java)
public class Item {

    private Long id;
    private String name;
    private Double price;

    public Item() {
    }
    
    public Item(String name, Double price) {
        this.name = name;
        this.price = price;
    }
    
    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }
    
    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Double getPrice() {
        return price;
    }

    public void setPrice(Double price) {
        this.price = price;
    }
    
    @Override
    public String toString() {
        return "Item{" + "name=" + name + ", price=" + price + '}';
    }
}

Source code (ObjectToJSON.java)
import com.google.gson.Gson;
import com.javaquery.bean.Item;
import java.util.Arrays;
import java.util.List;

/**
 * Convert Java object to json using gson.
 * @author javaQuery
 * @date 24th March, 2017
 * @Github: https://github.com/javaquery/Examples
 */
public class ObjectToJSON {
    public static void main(String[] args) {
        /* Java object */
        Item iPhone = new Item("iPhone 7", 100.12);
        Item blackBerry = new Item("Black Berry", 50.12);
        List<Item> items = Arrays.asList(iPhone, blackBerry);
        
        Gson gson = new Gson();
        
        /* Convert single Object to JSON */
        String jsonObjectString = gson.toJson(iPhone);
        System.out.println(jsonObjectString);
        
        /* Convert List of Object to JSON */
        String jsonArrayString = gson.toJson(items);
        System.out.println(jsonArrayString);
    }
}

Output
{"name":"iPhone 7","price":100.12}
[{"name":"iPhone 7","price":100.12},{"name":"Black Berry","price":50.12}]

Source code (JSONToObject.java)
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.javaquery.bean.Item;
import java.lang.reflect.Type;
import java.util.List;

/**
 * Convert json string to java object using gson.
 * @author javaQuery
 * @date 24th March, 2017
 * @Github: https://github.com/javaquery/Examples
 */
public class JSONToObject {
    public static void main(String[] args) {
        String jsonObjectString = "{\"name\":\"iPhone 7\",\"price\":100.12}";
        String jsonArrayString = "[{\"name\":\"iPhone 7\",\"price\":100.12},{\"name\":\"Black Berry\",\"price\":50.12}]";
        
        Gson gson = new Gson();
        
        /* Convert JSONObject String to Object */
        Item item = gson.fromJson(jsonObjectString, Item.class);
        System.out.println(item);
        
        /* Convert JSONArray String to Object */
        Type type = new TypeToken<List<Item>>(){}.getType();
        List<Item> items = gson.fromJson(jsonArrayString, type);
        System.out.println(items);
    }
}

Output
Item{name=iPhone 7, price=100.12}
[Item{name=iPhone 7, price=100.12}, Item{name=Black Berry, price=50.12}]

How to Prettify - Format - Beautify json in Java?

Lately I was working on web services of different websites. All of them gives response in either JSONObject or JSONArray. Reading JSON in eclipse console is pretty hard so searched over internet and found library called jackson-all.

Download libraryhttp://www.java2s.com/Code/Jar/j/Downloadjacksonall190jar.htm

Source code
import java.io.IOException;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.ObjectWriter;

/**
 * Example of formating raw JSON
 * @author Vicky Thakor
 */
public class PrettifyJSONExample {
    public static void main(String[] args) {
        try {
            String json = "{\"candidate\" : \"Vicky Thakor\", \"expertise\" : [\"Core Java\", \"J2EE\", \"Design Pattern\"]}";
            System.out.println("Unformatter json:" + json);
            /* Create required objects */
            ObjectMapper objectMapper = new ObjectMapper();
            Object object = objectMapper.readValue(json, Object.class);
            ObjectWriter objectWriter = objectMapper.writer().withDefaultPrettyPrinter();
            /* Get the formatted json */
            String formattedJSON = objectWriter.writeValueAsString(object);
            System.out.println("Formatter json:\n"+formattedJSON);
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
}

Output
Unformatter json:{"candidate" : "Vicky Thakor", "expertise" : ["Core Java", "J2EE", "Design Pattern"]}
Formatter json:
{
  "candidate" : "Vicky Thakor",
  "expertise" : [ "Core Java", "J2EE", "Design Pattern" ]
}