Now, load the jar file from your IDE.
For IntelliJ Idea:
For Gradle:
compile 'com.google.code.gson:gson:2.8.6'
For Maven:
Inside pom.xml
<dependency>
<groupid>com.google.code.gson</groupid>
<artifactid>gson</artifactid>
<version>2.8.6</version>
</dependency>
package jsonToMap;
import com.google.gson.Gson;
import com.google.gson.stream.JsonReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.Map;
public class JsonConverter {
public static void main(String[] args) {
String baseDir = System.getProperty("user.dir");
String jsonPath = baseDir+"/src/jsonToMap/resources/sample.json";
//convert json map to Map
Map jsonMap = getMapFromJson(jsonPath);
System.out.println(jsonMap);
}
private static Map getMapFromJson(String filePath){
Gson gson = new Gson();
JsonReader reader = null;
try {
reader = new JsonReader(new FileReader(filePath));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return gson.fromJson(reader, Map.class);
}
}
//sample.json
{
"text":"first text",
"digit":1234,
"boolean":true
}
If you want to convert the file which contains the JSON list to List, you can provide the class to convert as below.
//sample.json
[
{
"text":"first text",
"digit":1234,
"boolean":true
},
{
"text":"second text",
"digit":1234,
"boolean":true
},
{
"text":"third text",
"digit":1234,
"boolean":true
}
]
/JsonConverter.java
private static List getListFromJson(String filePath){
Gson gson = new Gson();
JsonReader reader = null;
try {
reader = new JsonReader(new FileReader(filePath));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return gson.fromJson(reader, List.class);
}
If you want to convert to Custom class, create a class compatible with the fields from the JSON file and provide that class while converting. For e.g:
//sample.json
{
"text":"first text",
"digit":1234,
"aBoolean":true
}
//Sample.java
public class Sample {
private String text;
private Double digit;
private Boolean aBoolean;
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public Double getDigit() {
return digit;
}
public void setDigit(Double digit) {
this.digit = digit;
}
public Boolean getaBoolean() {
return aBoolean;
}
public void setaBoolean(Boolean aBoolean) {
this.aBoolean = aBoolean;
}
}
//JsonConverter.java
private static Sample getSampleFromJson(String filePath){
Gson gson = new Gson();
JsonReader reader = null;
try {
reader = new JsonReader(new FileReader(filePath));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return gson.fromJson(reader, Sample.class);
}
Here, we pass the class Sample while converting from the JSON. Make sure your JSON file and class structure match.
0 comments:
New comments are not allowed.