JSON을지도로 변환
JSON 코드를 다음과 같이 변환하는 가장 좋은 방법은 무엇입니까?
{
"data" :
{
"field1" : "value1",
"field2" : "value2"
}
}
Java Map에서 키가 (field1, field2)이고 해당 필드의 값은 (value1, value2)입니다.
어떤 아이디어? Json-lib를 사용해야합니까? 아니면 내 자신의 파서를 작성하면 더 좋습니까?
나는 당신이 당신 자신의 파서를 작성하는 것에 대해 농담하기를 바랍니다. :-)
이러한 간단한 매핑의 경우 http://json.org (섹션 java)의 대부분의 도구 가 작동합니다. 그중 하나 (Jackson, http://wiki.fasterxml.com/JacksonInFiveMinutes )의 경우 다음을 수행하십시오.
HashMap<String,Object> result =
new ObjectMapper().readValue(JSON_SOURCE, HashMap.class);
(여기서 JSON_SOURCE는 파일, 입력 스트림, 리더 또는 json 컨텐츠 문자열입니다)
나는 구글 gson 라이브러리를 좋아한다 .
json의 구조를 모르는 경우. 당신이 사용할 수있는
JsonElement root = new JsonParser().parse(jsonString);
그런 다음 json으로 작업 할 수 있습니다. 예를 들어 gson에서 "value1"을 얻는 방법 :
String value1 = root.getAsJsonObject().get("data").getAsJsonObject().get("field1").getAsString();
GSON 라이브러리 사용 :
import com.google.gson.Gson;
import com.google.common.reflect.TypeToken;
import java.lang.reclect.Type;
다음 코드를 사용하십시오.
Type mapType = new TypeToken<Map<String, Map>>(){}.getType();
Map<String, String[]> son = new Gson().fromJson(easyString, mapType);
JSON 라이브러리 사용 http://www.json.org/java/
// Assume you have a Map<String, String> in JSONObject jdata
@SuppressWarnings("unchecked")
Iterator<String> nameItr = jdata.keys();
Map<String, String> outMap = new HashMap<String, String>();
while(nameItr.hasNext()) {
String name = nameItr.next();
outMap.put(name, jdata.getString(name));
}
내 게시물은 다른 사람에게 도움이 될 수 있으므로 값에 특정 객체가있는지도가 있다고 상상해보십시오.
{
"shopping_list":{
"996386":{
"id":996386,
"label":"My 1st shopping list",
"current":true,
"nb_reference":6
},
"888540":{
"id":888540,
"label":"My 2nd shopping list",
"current":false,
"nb_reference":2
}
}
}
이 JSON 파일을 GSON 라이브러리로 구문 분석하면 쉽습니다. 프로젝트가 mavenized 된 경우
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.3.1</version>
</dependency>
그런 다음이 스 니펫을 사용하십시오.
import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
//Read the JSON file
JsonElement root = new JsonParser().parse(new FileReader("/path/to/the/json/file/in/your/file/system.json"));
//Get the content of the first map
JsonObject object = root.getAsJsonObject().get("shopping_list").getAsJsonObject();
//Iterate over this map
Gson gson = new Gson();
for (Entry<String, JsonElement> entry : object.entrySet()) {
ShoppingList shoppingList = gson.fromJson(entry.getValue(), ShoppingList.class);
System.out.println(shoppingList.getLabel());
}
해당 POJO는 다음과 같아야합니다.
public class ShoppingList {
int id;
String label;
boolean current;
int nb_reference;
//Setters & Getters !!!!!
}
그것이 도움이되기를 바랍니다!
이렇게하면지도처럼 작동합니다 ...
JSONObject fieldsJson = new JSONObject(json);
String value = fieldsJson.getString(key);
<dependency>
<groupId>org.codehaus.jettison</groupId>
<artifactId>jettison</artifactId>
<version>1.1</version>
</dependency>
나는 이렇게한다. 간단 해.
import java.util.Map;
import org.json.JSONObject;
import com.google.gson.Gson;
public class Main {
public static void main(String[] args) {
JSONObject jsonObj = new JSONObject("{ \"f1\":\"v1\"}");
@SuppressWarnings("unchecked")
Map<String, String> map = new Gson().fromJson(jsonObj.toString(),Map.class);
System.out.println(map);
}
}
java.lang.reflect.Type mapType = new TypeToken<Map<String, Object>>(){}.getType();
Gson gson = new Gson();
Map<String, Object> categoryicons = gson.fromJson(json, mapType );
JsonTools 라이브러리는 매우 완벽합니다. Github 에서 찾을 수 있습니다 .
Google의 Gson 2.7 (아마도 이전 버전이지만 2.7을 테스트 했음)을 사용하면 다음과 같이 간단합니다.
Map map = gson.fromJson(json, Map.class);
유형의 Map을 반환하고 class com.google.gson.internal.LinkedTreeMap
중첩 된 객체에서 재귀 적으로 작동합니다.
One more alternative is json-simple which can be found in Maven Central:
(JSONObject)JSONValue.parse(someString); //JSONObject is actually a Map.
The artifact is 24kbytes, doesn't have other runtime dependencies.
import net.sf.json.JSONObject
JSONObject.fromObject(yourJsonString).toMap
Underscore-java library can convert json string to hash map. I am the maintainer of the project.
Code example:
import com.github.underscore.lodash.U;
import java.util.*;
public class Main {
@SuppressWarnings("unchecked")
public static void main(String[] args) {
String json = "{"
+ " \"data\" :"
+ " {"
+ " \"field1\" : \"value1\","
+ " \"field2\" : \"value2\""
+ " }"
+ "}";
Map<String, Object> data = (Map) U.get((Map<String, Object>) U.fromJson(json), "data");
System.out.println(data);
// {field1=value1, field2=value2}
}
}
JSON to Map always gonna be a string/object data type. i haved GSON lib from google.
works very well and JDK 1.5 is the min requirement.
참고URL : https://stackoverflow.com/questions/443499/convert-json-to-map
'Programming' 카테고리의 다른 글
Xcode에서 프로젝트를 보관하면 다중 응용 프로그램 번들이 잘못 생성됩니다 (0) | 2020.05.25 |
---|---|
Android 에뮬레이터 오류 메시지 : "PANIC : 'x86'CPUS에 대한 에뮬레이터 엔진 프로그램이 없습니다." (0) | 2020.05.25 |
엔티티를 계산하는 코코아 코어 데이터 효율적인 방법 (0) | 2020.05.25 |
MySQL에서 기본 키 제거 (0) | 2020.05.25 |
리눅스에서 Xcode를 실행할 수 있습니까?SQL Server 문자열을 날짜로 변환 (0) | 2020.05.25 |