Gson: java object to json

Trabla: Gson: java json parser example


Gson library java object to json tutorial



Gson (also known as Google Gson) is an open source Java library to serialize and deserialize Java objects to (and from) JSON.
https://en.wikipedia.org/wiki/Gson

Solving:

1. Download Gson jar from "The Central Repository"

http://search.maven.org/#artifactdetails%7Ccom.google.code.gson%7Cgson%7C2.6.2%7Cjar

Gson library java object to json tutorial screenshot 1


2. Drag-n-drop Gson .jar into your Eclipse project source folder

Gson library java object to json tutorial screenshot 2


3. Right click on jar - add "Build path" -> "Add to build path"

Gson library java object to json tutorial screenshot 3

Gson library java object to json tutorial screenshot 4


4. Source code

package com.codingtrabla.demos;

import java.util.ArrayList;
import java.util.List;

import com.google.gson.Gson;

public class GsonUsageDemo {

public static void main(String[] args) {

Gson gson = new Gson();

List<String> list = new ArrayList<String>();

list.add("New York");
list.add("London");
list.add("Sydney");

String json = gson.toJson( list );

System.out.println(json);

}

}

Gson library java object to json tutorial screenshot 5

Gson library java object to json tutorial screenshot 6



Output:
["New York","London","Sydney"]

Gson library java object to json tutorial screenshot 7












No comments:

Post a Comment