GSON 라이브러리를 사용하여 Java의 맵 키 값에 해당하는 구조 객체를 JSON으로 변환
(GSON의 GitHub 프로젝트 페이지:https://github.com/google/gson)
JavaBean
이 예에서는 Json을 일반 JavaBean 객체로 되돌릴 때 TypeToken의 정의를 중점적으로 살펴봅니다.
엔티티 클래스:
public class Point {
private int x;
private int y;
public Point(int x, int y) {
this.x = x;
this.y = y;
}
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
@Override
public String toString() {
return "Point [x=" + x + ", y=" + y + "]";
}
}
테스트 클래스:
import java.util.LinkedHashMap;
import java.util.Map;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
public class GsonTest3 {
public static void main(String[] args) {
Gson gson = new GsonBuilder().enableComplexMapKeySerialization()
.create();
Map<Point, String> map1 = new LinkedHashMap<Point, String>();// LinkedHashMap
map1.put(new Point(5, 6), "a");
map1.put(new Point(8, 8), "b");
String s = gson.toJson(map1);
System.out.println(s);// :[[{"x":5,"y":6},"a"],[{"x":8,"y":8},"b"]]
Map<Point, String> retMap = gson.fromJson(s,
new TypeToken<Map<Point, String>>() {
}.getType());
for (Point p : retMap.keySet()) {
System.out.println("key:" + p + " values:" + retMap.get(p));
}
System.out.println(retMap);
System.out.println("----------------------------------");
Map<String, Point> map2 = new LinkedHashMap<String, Point>();
map2.put("a", new Point(3, 4));
map2.put("b", new Point(5, 6));
String s2 = gson.toJson(map2);
System.out.println(s2);
Map<String, Point> retMap2 = gson.fromJson(s2,
new TypeToken<Map<String, Point>>() {
}.getType());
for (String key : retMap2.keySet()) {
System.out.println("key:" + key + " values:" + retMap2.get(key));
}
}
}
결과:
[[{"x":5,"y":6},"a"],[{"x":8,"y":8},"b"]]
key:Point [x=5, y=6] values:a
key:Point [x=8, y=8] values:b
{Point [x=5, y=6]=a, Point [x=8, y=8]=b}
----------------------------------
{"a":{"x":3,"y":4},"b":{"x":5,"y":6}}
key:a values:Point [x=3, y=4]
key:b values:Point [x=5, y=6]
범용 목록엔티티 클래스:
import java.util.Date;
public class Student {
private int id;
private String name;
private Date birthDay;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Date getBirthDay() {
return birthDay;
}
public void setBirthDay(Date birthDay) {
this.birthDay = birthDay;
}
@Override
public String toString() {
return "Student [birthDay=" + birthDay + ", id=" + id + ", name="
+ name + "]";
}
}
public class Teacher {
private int id;
private String name;
private String title;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
@Override
public String toString() {
return "Teacher [id=" + id + ", name=" + name + ", title=" + title
+ "]";
}
}
테스트 클래스:
package com.tgb.lk.demo.gson.test4;
import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
public class GsonTest4 {
public static void main(String[] args) {
Student student1 = new Student();
student1.setId(1);
student1.setName(" ");
student1.setBirthDay(new Date());
Student student2 = new Student();
student2.setId(2);
student2.setName(" ");
student2.setBirthDay(new Date());
Student student3 = new Student();
student3.setId(3);
student3.setName(" ");
student3.setBirthDay(new Date());
List<Student> stulist = new ArrayList<Student>();
stulist.add(student1);
stulist.add(student2);
stulist.add(student3);
Teacher teacher1 = new Teacher();
teacher1.setId(1);
teacher1.setName(" ");
teacher1.setTitle(" ");
Teacher teacher2 = new Teacher();
teacher2.setId(2);
teacher2.setName(" ");
teacher2.setTitle(" ");
List<Teacher> teacherList = new ArrayList<Teacher>();
teacherList.add(teacher1);
teacherList.add(teacher2);
Map<String, Object> map = new LinkedHashMap<String, Object>();
map.put("students", stulist);
map.put("teachers", teacherList);
Gson gson = new Gson();
String s = gson.toJson(map);
System.out.println(s);
System.out.println("----------------------------------");
Map<String, Object> retMap = gson.fromJson(s,
new TypeToken<Map<String, List<Object>>>() {
}.getType());
for (String key : retMap.keySet()) {
System.out.println("key:" + key + " values:" + retMap.get(key));
if (key.equals("students")) {
List<Student> stuList = (List<Student>) retMap.get(key);
System.out.println(stuList);
} else if (key.equals("teachers")) {
List<Teacher> tchrList = (List<Teacher>) retMap.get(key);
System.out.println(tchrList);
}
}
}
}
출력 결과:
{"students":[{"id":1,"name":" ","birthDay":"Jun 22, 2012 9:48:19 PM"},{"id":2,"name":" ","birthDay":"Jun 22, 2012 9:48:19 PM"},{"id":3,"name":" ","birthDay":"Jun 22, 2012 9:48:19 PM"}],"teachers":[{"id":1,"name":" ","title":" "},{"id":2,"name":" ","title":" "}]}
----------------------------------
key:students values:[{id=1.0, name= , birthDay=Jun 22, 2012 9:48:19 PM}, {id=2.0, name= , birthDay=Jun 22, 2012 9:48:19 PM}, {id=3.0, name= , birthDay=Jun 22, 2012 9:48:19 PM}]
[{id=1.0, name= , birthDay=Jun 22, 2012 9:48:19 PM}, {id=2.0, name= , birthDay=Jun 22, 2012 9:48:19 PM}, {id=3.0, name= , birthDay=Jun 22, 2012 9:48:19 PM}]
key:teachers values:[{id=1.0, name= , title= }, {id=2.0, name= , title= }]
[{id=1.0, name= , title= }, {id=2.0, name= , title= }]
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
Java의 JSON 형식 변환 라이브러리 GSON의 초기 사용 노트이제 Java 객체를 JSON으로 변환할 수 있는 소스 오픈 프로젝트가 있습니다.그러나 대부분의 항목은 클래스 파일에 자바 주석을 넣으라고 요구하지만, 원본 코드를 바꿀 수 없을 때는 할 수 없다.또한 Java 범주...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.