Java의 모델 클래스에서 직접 JSON 개체 만들기
나는 모델 수업을 몇 개 듣는다.Customer,Product여러 개의 필드와 세터-게터 메서드를 가진 프로젝트에서 소켓을 통해 클라이언트와 서버 간에 JSONObject로 이러한 클래스의 오브젝트를 교환해야 합니다.
내가 어떻게 할 수 있는 방법은 없을까?JSONObject모델 클래스의 객체에서 직접 전송하여 객체의 필드가 키가 되고 해당 모델 클래스 객체의 값이 이 JSONObject의 값이 됩니다.
예:
Customer c = new Customer();
c.setName("Foo Bar");
c.setCity("Atlantis");
.....
/* More such setters and corresponding getters when I need the values */
.....
JSON 오브젝트는 다음과 같이 작성합니다.
JSONObject jsonc = new JSONObject(c); //I'll use this only once I'm done setting all values.
그 결과 다음과 같은 결과가 나왔습니다.
{"name":"Foo Bar","city":"Atlantis"...}
일부 모델 클래스에서는 특정 속성 자체가 다른 모델 클래스의 객체입니다.예를 들어 다음과 같습니다.
Product p = new Product();
p.setName("FooBar Cookies");
p.setProductType("Food");
c.setBoughtProduct(p);
위와 같은 경우 예상대로 JSON 오브젝트는 다음과 같습니다.
{"name":"Foo Bar","city":"Atlantis","bought":{"productname":"FooBar Cookies","producttype":"food"}}
제가 이런 걸 만들 수 있다는 걸 알아요toJSONString()각 모델 클래스의 JSON 친화적인 스트링을 만들고 조작하도록 합니다만, Java에서 RESTful 서비스를 작성한 이전의 경험(이 질문에서는 전혀 문맥에 맞지 않음)에서는, JSON 스트링을 사용하여 서비스 메서드에서 반환할 수 있었습니다.@Produces(MediaType.APPLICATION_JSON)model class의 오브젝트를 반환하는 메서드를 가지고 있습니다.클라이언트 측에서 소비할 수 있는 JSON 스트링이 생성되었습니다.
현재 시나리오에서도 비슷한 행동을 할 수 있는지 궁금합니다.
Google GSON은 이 기능을 합니다.저는 여러 프로젝트에 사용해 왔습니다만, 심플하고, 동작도움이 됩니다.간단한 오브젝트 번역은 개입 없이 할 수 있지만 (양방향으로) 커스터마이즈하는 메커니즘도 있습니다.
Gson g = ...;
String jsonString = g.toJson(new Customer());
여기에는 Gson을 사용할 수 있습니다.
Maven 의존관계:
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.0</version>
</dependency>
자바 코드:
Customer customer = new Customer();
Product product = new Product();
// Set your values ...
Gson gson = new Gson();
String json = gson.toJson(customer);
Customer deserialized = gson.fromJson(json, Customer.class);
User = new User();
Gson gson = new Gson();
String jsonString = gson.toJson(user);
try {
JSONObject request = new JSONObject(jsonString);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
이를 위해 gson을 사용합니다.다음 코드를 사용하여 json을 가져올 수 있습니다.
Gson gson = new Gson();
String json = gson.toJson(yourObject);
XStream 파서를 사용하여
Product p = new Product();
p.setName("FooBar Cookies");
p.setProductType("Food");
c.setBoughtProduct(p);
XStream xstream = new XStream(new JettisonMappedXmlDriver());
xstream.setMode(XStream.NO_REFERENCES);
xstream.alias("p", Product.class);
String jSONMsg=xstream.toXML(product);
System.out.println(xstream.toXML(product));
그러면 JSON 문자열 배열이 나타납니다.
언급URL : https://stackoverflow.com/questions/10930624/creating-json-objects-directly-from-model-classes-in-java
'programing' 카테고리의 다른 글
| Elastic Search 서버에서 json 파일(문서 100장)을 Import할 수 있는 방법이 있습니까? (0) | 2023.04.04 |
|---|---|
| Java 스크립트 파일, Visual Studio에서 영역을 추가하는 방법 (0) | 2023.04.04 |
| CORS 정책에 의해 액세스가 차단되었습니다.비행 전 요청에 대한 응답이 액세스 제어 검사를 통과하지 못했습니다. (0) | 2023.04.04 |
| Wordpress 4.2.2 업데이트 실패 wpdb-> 삽입 (0) | 2023.04.04 |
| Wordpress ACF - 날짜 형식 (0) | 2023.04.04 |