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 목록을 추출하는 것입니다.구글의 Gson을 잠재적인 JSON 플러그인으로 보았습니다.이 JSON 문자열에서 Java를 생성하는 방법에 대해 어떤 형태로든 지침을 제공할 수 있습니까?
구글의 Gson을 잠재적인 JSON 플러그인으로 보았습니다.이 JSON 문자열에서 Java를 생성하는 방법에 대해 어떤 형태로든 지침을 제공할 수 있습니까?
Google Gson은 제네릭스와 네스트 콩을 지원합니다.그[]
는 배열을 나타내며 플레인 Java 배열과 같은 Java 컬렉션에 매핑해야 합니다.그{}
JSON은 개체를 나타내며 Java 또는 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을 가지고 있는 것만으로 문의해 주십시오.
다음 항목도 참조하십시오.
지손의 비와아아!매우 멋지고 훌륭하지만, 간단한 오브젝트 이외의 것을 하고 싶은 순간, 간단하게 독자적인 시리얼 라이저를 작성할 필요가 있습니다(그것은 그다지 어렵지 않습니다).
또한 개체 배열이 있고 일부 json을 해당 개체 배열로 역직렬화하면 실제 유형은 LOST입니다!전체 개체는 복사조차 되지 않습니다!XStream 사용..jsondriver를 사용하여 적절한 설정을 하면 추악한 타입을 실제 json으로 인코딩하여 아무것도 흐트러뜨리지 않습니다.진정한 시리얼라이제이션에는 약간의 대가(추악한 json)가 필요합니다.
Jackson은 이러한 문제를 수정하고 GSON보다 속도가 빠릅니다.
이상하게도 지금까지 언급된 괜찮은 JSON 프로세서는 GSON뿐입니다.
다음은 더 좋은 선택지입니다.
- Jackson(Github) -- 강력한 데이터 바인딩(POJO 간 JSON), 스트리밍(초고속), 트리 모델(입력되지 않은 액세스에 편리함)
- Flex-JSON - 구성이 용이한 시리얼화
편집 (2013년 8월):
하나 더 고려해야 할 사항:
- Genson - Jackson과 유사한 기능으로 개발자가 쉽게 설정할 수 있습니다.
아니면 잭슨과 함께:
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");
기타.
변환이 간단하고 동작하는 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);
}
}
Load From J(로드 시작 J)SON.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");
입력 JSON 형식(문자열/파일)에 따라 jSONtring을 만듭니다.JSON에 대응하는 샘플 메시지클래스 오브젝트는 다음과 같이 취득할 수 있습니다.
Message msgFromJSON = new ObjectMapper().readValue(jSONString, Message.class);
혜택 시도:
https://github.com/RichardHightower/boon
너무 빨라요.
https://github.com/RichardHightower/json-parsers-benchmark
내 말을 믿지 마...개틀링 벤치마크를 확인하십시오.
https://github.com/gatling/json-parsers-benchmark
(최대 4배인 경우도 있고, 테스트의 100점 만점에 해당합니다.더 빠른 인덱스 오버레이 모드도 갖추고 있습니다.아직 젊지만 이미 사용자가 있습니다.)
JSON to Maps and Lists를 다른 lib가 JSON DOM에 해석할 수 있는 속도보다 빠르게 해석할 수 있습니다.이것은 인덱스 오버레이 모드가 아닙니다.Boon Index Overlay 모드를 사용하면 더 빠릅니다.
또한 매우 빠른 JSON lax 모드와 PLIST 파서 모드도 갖추고 있습니다. :) (또한 UTF-8 인코딩을 사용하는 바이트모드에서 직접 전송되는 초저메모리를 갖추고 있습니다).
또한 JSON에서 JavaBean 모드로 가장 빠릅니다.
새로운 것이지만, 속도와 심플한 API가 당신이 원하는 것이라면, 더 빠르거나 미니멀리즘적인 API는 없다고 생각합니다.
가장 쉬운 방법은 이 softconvertvalue 메서드를 사용하는 것입니다.이 메서드는 jsonData를 특정 Dto 클래스로 변환할 수 있는 커스텀 메서드입니다.
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);
}
언급URL : https://stackoverflow.com/questions/1688099/converting-json-data-to-java-object
'programing' 카테고리의 다른 글
Foreach(Vuex)의 상태로부터 요소를 참조하려면 어떻게 해야 합니까? (0) | 2022.08.02 |
---|---|
Java의 불변 배열 (0) | 2022.07.19 |
Vuejs - vuex 계산 속성, DOM이 업데이트되지 않음 (0) | 2022.07.19 |
VueJ에서 렌더링 목록 항목의 innerText를 가져오는 방법s (0) | 2022.07.19 |
vue submit 버튼 데이터 (0) | 2022.07.19 |