Java에서 jsonString을 JSONObject로 변환하는 방법
String 변수를 호출했습니다.jsonString
:
{"phonetype":"N95","cat":"WP"}
이제 JSON 개체로 변환합니다.구글에서 더 검색해봤지만 예상된 답변이 나오지 않았어!
try {
JSONObject jsonObject = new JSONObject("{\"phonetype\":\"N95\",\"cat\":\"WP\"}");
}catch (JSONException err){
Log.d("Error", err.toString());
}
아직 답을 찾고 계신 분께:
JSONParser parser = new JSONParser();
JSONObject json = (JSONObject) parser.parse(stringToParse);
하시면 됩니다.google-gson
★★★★★★★★★★★★★★★★★★:
오브젝트 예시
class BagOfPrimitives {
private int value1 = 1;
private String value2 = "abc";
private transient int value3 = 3;
BagOfPrimitives() {
// no-args constructor
}
}
(시리얼라이제이션)
BagOfPrimitives obj = new BagOfPrimitives();
Gson gson = new Gson();
String json = gson.toJson(obj);
==> json is {"value1":1,"value2":"abc"}
순환 참조를 사용하면 무한 재귀가 발생하므로 개체를 직렬화할 수 없습니다.
(탈직렬화)
BagOfPrimitives obj2 = gson.fromJson(json, BagOfPrimitives.class);
==> obj2 is just like obj
Gson의 다른 예는 다음과 같습니다.
Gson은 학습과 구현이 용이하며 다음 두 가지 방법을 알아야 합니다.
-> toJson() – Java 객체를 JSON 형식으로 변환합니다.
-> from Json() - JSON을 Java 객체로 변환합니다.
import com.google.gson.Gson;
public class TestObjectToJson {
private int data1 = 100;
private String data2 = "hello";
public static void main(String[] args) {
TestObjectToJson obj = new TestObjectToJson();
Gson gson = new Gson();
//convert java object to JSON format
String json = gson.toJson(obj);
System.out.println(json);
}
}
산출량
{"data1":100,"data2":"hello"}
자원:
JSON 홈페이지에는 다양한 Java JSON 시리얼라이저와 디시리얼라이저가 링크되어 있습니다.
이 글에서 현재 22개의 항목이 있습니다.
...물론 리스트는 바뀔 수 있습니다.
Java 7 솔루션
import javax.json.*;
...
String TEXT;
JsonObject body = Json.createReader(new StringReader(TEXT)).readObject()
;
String
JSONObject
만 요.String
를 constructor 설 instance instance 。JSONObject
.
예:
JSONObject jsonObj = new JSONObject("your string");
를 사용하여 JSON에 대한 문자열Jackson
com.fasterxml.jackson.databind
:
json-string은 다음과 같이 표현된다고 가정합니다.jsonString = {"phontype":"N95","cat":WP"}
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
/**
* Simple code exmpl
*/
ObjectMapper mapper = new ObjectMapper();
JsonNode node = mapper.readTree(jsonString);
String phoneType = node.get("phonetype").asText();
String cat = node.get("cat").asText();
저는 google-gson을 사용하는 것을 좋아합니다.JSONObject를 직접 사용할 필요가 없기 때문입니다.
이 경우 JSON 오브젝트의 속성에 대응하는 클래스가 있습니다.
class Phone {
public String phonetype;
public String cat;
}
...
String jsonString = "{\"phonetype\":\"N95\",\"cat\":\"WP\"}";
Gson gson = new Gson();
Phone fooFromJson = gson.fromJson(jsonString, Phone.class);
...
그러나 당신의 질문은 "어떻게 하면 JSON String에서 실제 JSONObject 오브젝트를 얻을 수 있을까?"에 가깝다고 생각합니다.
google-json api를 보고 있었는데 org.json api만큼 간단한 것을 찾을 수 없었습니다.이것은 아마 베어본 JSONObject를 그렇게 강하게 사용하고 싶은 경우일 것입니다.
http://www.json.org/javadoc/org/json/JSONObject.html
org.json과 함께.JSONObject(또 다른 완전히 다른 API) 다음과 같은 작업을 수행할 수 있습니다.
JSONObject jsonObject = new JSONObject("{\"phonetype\":\"N95\",\"cat\":\"WP\"}");
System.out.println(jsonObject.getString("phonetype"));
구글-gson의 장점은 JSONObject와 거래할 필요가 없다는 것이라고 생각합니다.json을 잡고 클래스 속성을 전달하여 역직렬화하면 클래스 속성이 JSON과 일치합니다.다만, 역직렬화 측에서 사전 매핑된 클래스를 가질 여유는 없습니다.JSON 생성 측에서는 상황이 너무 역동적일 수 있기 때문입니다.이 경우는, json.org 를 사용해 주세요.
org.json을 Import해야 합니다.
JSONObject jsonObj = null;
try {
jsonObj = new JSONObject("{\"phonetype\":\"N95\",\"cat\":\"WP\"}");
} catch (JSONException e) {
e.printStackTrace();
}
Codehouse Jackson - 저는 2012년부터 RESTful 웹 서비스와 JUnit 테스트를 위해 이 멋진 API를 하고 있습니다.API를 사용하면 다음 작업을 수행할 수 있습니다.
(1) JSON 문자열을 Java bean으로 변환
public static String beanToJSONString(Object myJavaBean) throws Exception {
ObjectMapper jacksonObjMapper = new ObjectMapper();
return jacksonObjMapper.writeValueAsString(myJavaBean);
}
(2) JSON 문자열을 JSON 개체(JsonNode)로 변환
public static JsonNode stringToJSONObject(String jsonString) throws Exception {
ObjectMapper jacksonObjMapper = new ObjectMapper();
return jacksonObjMapper.readTree(jsonString);
}
//Example:
String jsonString = "{\"phonetype\":\"N95\",\"cat\":\"WP\"}";
JsonNode jsonNode = stringToJSONObject(jsonString);
Assert.assertEquals("Phonetype value not legit!", "N95", jsonNode.get("phonetype").getTextValue());
Assert.assertEquals("Cat value is tragic!", "WP", jsonNode.get("cat").getTextValue());
(3) Java bean을 JSON 문자열로 변환
public static Object JSONStringToBean(Class myBeanClass, String JSONString) throws Exception {
ObjectMapper jacksonObjMapper = new ObjectMapper();
return jacksonObjMapper.readValue(JSONString, beanClass);
}
참조:
JsonNode API - JsonNode 개체에서 값을 사용, 탐색, 구문 분석 및 평가하는 방법
튜토리얼 - Jackson을 사용하여 JSON 문자열을 JsonNode로 변환하는 간단한 튜토리얼
org.json.simple을 사용하여 문자열을 Json 개체로 변환합니다.JSONObject
private static JSONObject createJSONObject(String jsonString){
JSONObject jsonObject=new JSONObject();
JSONParser jsonParser=new JSONParser();
if ((jsonString != null) && !(jsonString.isEmpty())) {
try {
jsonObject=(JSONObject) jsonParser.parse(jsonString);
} catch (org.json.simple.parser.ParseException e) {
e.printStackTrace();
}
}
return jsonObject;
}
http://json-lib.sourceforge.net(net.disc.json)을 사용하고 있는 경우.JSONObject)
매우 간단합니다.
String myJsonString;
JSONObject json = JSONObject.fromObject(myJsonString);
또는
JSONObject json = JSONSerializer.toJSON(myJsonString);
그런 다음 json.getString(param), json.getInt(param) 등을 사용하여 값을 가져옵니다.
문자열을 json으로 변환하고 sring은 json과 같습니다.{"phontype""N95", cat":WP"}
String Data=response.getEntity().getText().toString(); // reading the string value
JSONObject json = (JSONObject) new JSONParser().parse(Data);
String x=(String) json.get("phonetype");
System.out.println("Check Data"+x);
String y=(String) json.get("cat");
System.out.println("Check Data"+y);
Generic Json Parsing에는 fasterxml의 JsonNode를 사용합니다.내부적으로 모든 입력에 대한 키 값의 맵을 만듭니다.
예:
private void test(@RequestBody JsonNode node)
입력 문자열:
{"a":"b","c":"d"}
외부 라이브러리를 사용할 필요가 없습니다.
대신 이 클래스를 사용할 수 있습니다:). (짝수 목록, 중첩 목록 및 json을 처리합니다.)
public class Utility {
public static Map<String, Object> jsonToMap(Object json) throws JSONException {
if(json instanceof JSONObject)
return _jsonToMap_((JSONObject)json) ;
else if (json instanceof String)
{
JSONObject jsonObject = new JSONObject((String)json) ;
return _jsonToMap_(jsonObject) ;
}
return null ;
}
private static Map<String, Object> _jsonToMap_(JSONObject json) throws JSONException {
Map<String, Object> retMap = new HashMap<String, Object>();
if(json != JSONObject.NULL) {
retMap = toMap(json);
}
return retMap;
}
private static Map<String, Object> toMap(JSONObject object) throws JSONException {
Map<String, Object> map = new HashMap<String, Object>();
Iterator<String> keysItr = object.keys();
while(keysItr.hasNext()) {
String key = keysItr.next();
Object value = object.get(key);
if(value instanceof JSONArray) {
value = toList((JSONArray) value);
}
else if(value instanceof JSONObject) {
value = toMap((JSONObject) value);
}
map.put(key, value);
}
return map;
}
public static List<Object> toList(JSONArray array) throws JSONException {
List<Object> list = new ArrayList<Object>();
for(int i = 0; i < array.length(); i++) {
Object value = array.get(i);
if(value instanceof JSONArray) {
value = toList((JSONArray) value);
}
else if(value instanceof JSONObject) {
value = toMap((JSONObject) value);
}
list.add(value);
}
return list;
}
}
JSON 문자열을 해시맵으로 변환하려면 다음 명령을 사용합니다.
HashMap<String, Object> hashMap = new HashMap<>(Utility.jsonToMap(
인터페이스를 역직렬화하는 GSON에서는 다음과 같은 예외가 발생합니다.
"java.lang.RuntimeException: Unable to invoke no-args constructor for interface XXX. Register an InstanceCreator with Gson for this type may fix this problem."
비직렬화 중에는 GSON은 그 인터페이스에 대해 어떤 오브젝트를 인텐테이션해야 하는지 알 수 없습니다.
이 문제는 여기서 어떻게든 해결되었다.
그러나 FlexJSON에는 본질적으로 이 솔루션이 있습니다.serialize time을 실행하면서 아래와 같이 json의 일부로 클래스 이름을 추가하고 있습니다.
{
"HTTPStatus": "OK",
"class": "com.XXX.YYY.HTTPViewResponse",
"code": null,
"outputContext": {
"class": "com.XXX.YYY.ZZZ.OutputSuccessContext",
"eligible": true
}
}
그래서 JSON은 조금 더 커밍아웃하지만 쓸 필요는 없습니다.InstanceCreator
이는 GSON에서 필요합니다.
org.json 사용
JSON 형식의 텍스트를 포함하는 문자열이 있는 경우 다음 단계를 수행하여 JSON 개체를 가져올 수 있습니다.
String jsonString = "{\"phonetype\":\"N95\",\"cat\":\"WP\"}";
JSONObject jsonObj = null;
try {
jsonObj = new JSONObject(jsonString);
} catch (JSONException e) {
e.printStackTrace();
}
이제 음종류에 액세스합니다.
Sysout.out.println(jsonObject.getString("phonetype"));
추천 해제 문제로 인해 게시된 답변에서 해결책을 찾지 못한 사용자는 다음을 사용할 수 있습니다.JsonParser
com.google.gson에서.
예:
JsonObject jsonObject = JsonParser.parseString(jsonString).getAsJsonObject();
System.out.println(jsonObject.get("phonetype"));
System.out.println(jsonObject.get("cat"));
json 단일 개체를 목록으로 설정하기 위해,
"locations":{
}
안으로List<Location>
사용하다
ObjectMapper mapper = new ObjectMapper();
mapper.configure(DeserializationConfig.Feature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true);
jackson.mapper-asl-1.9.7.jar
보다 심플한 방법으로 도입하는 것이 좋습니다.org.json
lib. 다음과 같이 매우 간단한 방법을 수행합니다.
JSONObject obj = new JSONObject();
obj.put("phonetype", "N95");
obj.put("cat", "WP");
지금이다obj
변환된 상태입니까?JSONObject
각 String의 형식을 지정합니다.이름-값 쌍이 있는 경우입니다.
의 경우, 직접 할 수 .JSONObject
json String
그렇지 않으면 예외가 발생하게 됩니다.
언급URL : https://stackoverflow.com/questions/5245840/how-to-convert-jsonstring-to-jsonobject-in-java
'programing' 카테고리의 다른 글
Vuetify 대화상자를 프로그래밍 방식으로 실행하고 응답을 기다리는 방법 (0) | 2022.08.02 |
---|---|
Laravel 프로젝트의 Vue.use(VueResource) 문자열은 어디에 있습니까? (0) | 2022.08.02 |
Vuex 및 Composition API를 사용하여 사후 대응 속성에 액세스할 수 있는 방법이 있습니까? (0) | 2022.08.02 |
Java에서 정적 메서드를 추상화할 수 없는 이유는 무엇입니까? (0) | 2022.08.02 |
vue v-model 지시문의 개체 경로로 점 구분 문자열을 사용하는 방법 (0) | 2022.08.02 |