JSON 데이터를 Java 객체로 변환합니다
문제
Java 액션 방법의 JSON 문자열에서 속성에 액세스 할 수 있기를 원합니다. 문자열은 간단히 말하면 사용할 수 있습니다 myJsonString = object.getJson()
. 아래는 문자열이 어떻게 보일 수 있는지에 대한 예입니다.
{
'title': 'ComputingandInformationsystems',
'id': 1,
'children': 'true',
'groups': [{
'title': 'LeveloneCIS',
'id': 2,
'children': 'true',
'groups': [{
'title': 'IntroToComputingandInternet',
'id': 3,
'children': 'false',
'groups': []
}]
}]
}
이 문자열에서 모든 JSON 객체에는 다른 JSON 객체 배열이 포함되어 있습니다. 의도는 다른 JSON 객체를 포함하는 그룹 속성을 소유 한 주어진 객체가있는 ID 목록을 추출하는 것입니다. Google의 GSON을 잠재적 인 JSON 플러그인으로 보았습니다. 누구 든지이 JSON 문자열에서 Java를 생성 할 수있는 방법에 대한 지침을 제공 할 수 있습니까?
해결책
Google의 GSON을 잠재적 인 JSON 플러그인으로 보았습니다. 누구 든지이 JSON 문자열에서 Java를 생성 할 수있는 방법에 대한 지침을 제공 할 수 있습니까?
Google Gson 제네릭과 중첩 콩을 지원합니다. 그만큼 []
JSON에서는 배열을 나타내며 다음과 같은 Java 컬렉션에 매핑되어야합니다. List
또는 단지 평범한 자바 어레이. 그만큼 {}
JSON에서 객체를 나타내고 Java에 매핑해야합니다. Map
또는 일부 Javabean 클래스.
여러 속성이있는 JSON 객체가 있습니다. groups
속성은 동일한 유형의 중첩 된 객체의 배열을 나타냅니다. 이것은 다음과 같은 방법으로 GSON과 구문 분석 할 수 있습니다.
package com.stackoverflow.q1688099;
import java.util.List;
import com.google.gson.Gson;
public class Test {
public static void main(String... args) throws Exception {
String json =
"{"
+ "'title': 'Computing and Information systems',"
+ "'id' : 1,"
+ "'children' : 'true',"
+ "'groups' : [{"
+ "'title' : 'Level one CIS',"
+ "'id' : 2,"
+ "'children' : 'true',"
+ "'groups' : [{"
+ "'title' : 'Intro To Computing and Internet',"
+ "'id' : 3,"
+ "'children': 'false',"
+ "'groups':[]"
+ "}]"
+ "}]"
+ "}";
// Now do the magic.
Data data = new Gson().fromJson(json, Data.class);
// Show it.
System.out.println(data);
}
}
class Data {
private String title;
private Long id;
private Boolean children;
private List<Data> groups;
public String getTitle() { return title; }
public Long getId() { return id; }
public Boolean getChildren() { return children; }
public List<Data> getGroups() { return groups; }
public void setTitle(String title) { this.title = title; }
public void setId(Long id) { this.id = id; }
public void setChildren(Boolean children) { this.children = children; }
public void setGroups(List<Data> groups) { this.groups = groups; }
public String toString() {
return String.format("title:%s,id:%d,children:%s,groups:%s", title, id, children, groups);
}
}
상당히 간단하지 않습니까? 적절한 Javabean을 가지고 전화하십시오 Gson#fromJson()
.
또한보십시오:
- json.org - JSON 소개
- GSON 사용자 안내서 - GSON 소개
다른 팁
또는 잭슨과 함께 :
String json = "...
ObjectMapper m = new ObjectMapper();
Set<Product> products = m.readValue(json, new TypeReference<Set<Product>>() {});
어떤 변경 으로든 이미 사용하는 응용 프로그램에있는 경우 http://restfb.com/ 그런 다음 할 수 있습니다 :
import com.restfb.json.JsonObject;
...
JsonObject json = new JsonObject(jsonString);
json.get("title");
등.
특수 맵의 키나 값과 함께 특별한 맵을 사용하는 경우 Google 구현에 의해 고려되지 않는다는 것을 알게 될 것입니다.
쉽고 작동하는 Java 코드를 변환 할 수 있습니다 JSONObject
에게 Java Object
직원. 자바
import java.util.HashMap;
import java.util.Map;
import javax.annotation.Generated;
import com.fasterxml.jackson.annotation.JsonAnyGetter;
import com.fasterxml.jackson.annotation.JsonAnySetter;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
@JsonInclude(JsonInclude.Include.NON_NULL)
@Generated("org.jsonschema2pojo")
@JsonPropertyOrder({
"id",
"firstName",
"lastName"
})
public class Employee {
@JsonProperty("id")
private Integer id;
@JsonProperty("firstName")
private String firstName;
@JsonProperty("lastName")
private String lastName;
@JsonIgnore
private Map<String, Object> additionalProperties = new HashMap<String, Object>();
/**
*
* @return
* The id
*/
@JsonProperty("id")
public Integer getId() {
return id;
}
/**
*
* @param id
* The id
*/
@JsonProperty("id")
public void setId(Integer id) {
this.id = id;
}
/**
*
* @return
* The firstName
*/
@JsonProperty("firstName")
public String getFirstName() {
return firstName;
}
/**
*
* @param firstName
* The firstName
*/
@JsonProperty("firstName")
public void setFirstName(String firstName) {
this.firstName = firstName;
}
/**
*
* @return
* The lastName
*/
@JsonProperty("lastName")
public String getLastName() {
return lastName;
}
/**
*
* @param lastName
* The lastName
*/
@JsonProperty("lastName")
public void setLastName(String lastName) {
this.lastName = lastName;
}
@JsonAnyGetter
public Map<String, Object> getAdditionalProperties() {
return this.additionalProperties;
}
@JsonAnySetter
public void setAdditionalProperty(String name, Object value) {
this.additionalProperties.put(name, value);
}
}
loadfromjson.java
import org.codehaus.jettison.json.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
public class LoadFromJSON {
public static void main(String args[]) throws Exception {
JSONObject json = new JSONObject();
json.put("id", 2);
json.put("firstName", "hello");
json.put("lastName", "world");
byte[] jsonData = json.toString().getBytes();
ObjectMapper mapper = new ObjectMapper();
Employee employee = mapper.readValue(jsonData, Employee.class);
System.out.print(employee.getLastName());
}
}
HashMap keyArrayList = new HashMap();
Iterator itr = yourJson.keys();
while (itr.hasNext())
{
String key = (String) itr.next();
keyArrayList.put(key, yourJson.get(key).toString());
}
표준 물건에 무슨 문제가 있습니까?
JSONObject jsonObject = new JSONObject(someJsonString);
JSONArray jsonArray = jsonObject.getJSONArray("someJsonArray");
String value = jsonArray.optJSONObject(i).getString("someJsonValue");
BOON을 시도해보십시오.
https://github.com/richardhightower/boon
빨리 사악합니다.
https://github.com/richardhightower/json-parsers-benchmark
내 말을 받아들이지 마세요 ... 개틀링 벤치 마크를 확인하십시오.
https://github.com/gatling/json-parsers-benchmark
(최대 4 배의 경우, 100 대의 테스트 중 하나입니다. 또한 더 빠른 색인 오버레이 모드도 있습니다. 젊지 만 이미 사용자가 있습니다.)
JSON은 다른 LIB가 JSON DOM으로 구문 분석 할 수있는 것보다 더 빠르게 JSON을 구문 분석 할 수 있으며 인덱스 오버레이 모드가 없습니다. BOON 인덱스 오버레이 모드에서는 훨씬 빠릅니다.
또한 매우 빠른 JSON LAX 모드와 PLIST 파서 모드가 있습니다. :) (그리고 UTF-8 인코딩이있는 바이트 모드에서 직접 메모리가 매우 낮습니다).
또한 JSON에서 Javabean 모드에서 가장 빠른 JSON도 있습니다.
그것은 새롭지 만 속도와 간단한 API가 당신이 찾고있는 것이라면 더 빠르거나 미니멀리스트 API가 있다고 생각하지 않습니다.
입력 JSON 형식 (문자열/파일)에 따라 jsonstring을 만듭니다. JSON에 해당하는 샘플 메시지 클래스 객체는 다음과 같이 얻을 수 있습니다.
메시지 msgfromjson = new ObjectMapper (). readValue (jsonstring, message.class);
가장 쉬운 방법은 JSONDATA를 특정 DTO 클래스로 변환 할 수있는 사용자 지정 메소드 인이 SoftConvertValue 메소드를 사용할 수 있다는 것입니다.
Dto response = softConvertValue(jsonData, Dto.class);
public static <T> T softConvertValue(Object fromValue, Class<T> toValueType)
{
ObjectMapper objMapper = new ObjectMapper();
return objMapper
.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
.convertValue(fromValue, toValueType);
}