JsonObject / JsonArray 값을 직접 수정하는 방법은 무엇입니까?
JSON String을 GSON에서 제공하는 JsonObject 클래스로 해석한 후(의미 있는 데이터 객체로 해석하는 것이 아니라 JsonObject를 엄격하게 사용하는 것으로 가정), 키의 필드/값을 직접 변경하려면 어떻게 해야 합니까?
도움이 될 만한 API가 보이지 않습니다.
https://static.javadoc.io/com.google.code.gson/gson/2.6.2/com/google/gson/JsonObject.html
이상하게도, 정답은 자산을 계속 다시 추가하는 것입니다.나는 반쯤 기대하고 있었다.setter방법.:S
System.out.println("Before: " + obj.get("DebugLogId")); // original "02352"
obj.addProperty("DebugLogId", "YYY");
System.out.println("After: " + obj.get("DebugLogId")); // now "YYY"
이는 다음 방법으로 하위 키 값을 수정할 때 작동합니다.JSONObject.사용되는 Import 입니다.
import org.json.JSONObject;
ex json:(입력으로서 제공하면서 json 파일을 문자열에 추가)
{
"parentkey1": "name",
"parentkey2": {
"childkey": "test"
},
}
코드
JSONObject jObject = new JSONObject(String jsoninputfileasstring);
jObject.getJSONObject("parentkey2").put("childkey","data1");
System.out.println(jObject);
출력:
{
"parentkey1": "name",
"parentkey2": {
"childkey": "data1"
},
}
Gson 라이브러리의 2.3 버전 이후 JsonArray 클래스에는 '세트' 메서드가 있습니다.
다음은 간단한 예입니다.
JsonArray array = new JsonArray();
array.add(new JsonPrimitive("Red"));
array.add(new JsonPrimitive("Green"));
array.add(new JsonPrimitive("Blue"));
array.remove(2);
array.set(0, new JsonPrimitive("Yelow"));
또 다른 접근법은 다음과 같은 방법으로 디시리얼라이즈하는 것입니다.java.util.MapJava를 수정하기만 하면 됩니다.Map원하는 대로이것에 의해, Java측의 데이터 처리와 데이터 전송 메카니즘(JSON)을 분리할 수 있습니다.이것이 코드를 정리하는 방법입니다.대체 데이터 구조가 아닌 데이터 전송에 JSON을 사용하는 방법입니다.
사실 이 모든 것은 문서에 나와 있습니다.
JSONObject 및 JSONArray를 모두 사용하여 표준 데이터 구조를 대체할 수 있습니다.
세터를 실장하려면 , 다음의 콜을 실시해 주세요.remove(String name)전에put(String name, Object value).
다음은 간단한 예입니다.
public class BasicDB {
private JSONObject jData = new JSONObject;
public BasicDB(String username, String tagline) {
try {
jData.put("username", username);
jData.put("tagline" , tagline);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public String getUsername () {
String ret = null;
try {
ret = jData.getString("username");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return ret;
}
public void setUsername (String username) {
try {
jData.remove("username");
jData.put("username" , username);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public String getTagline () {
String ret = null;
try {
ret = jData.getString("tagline");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return ret;
}
public static JSONObject convertFileToJSON(String fileName, String username, List<String> list)
throws FileNotFoundException, IOException, org.json.simple.parser.ParseException {
JSONObject json = new JSONObject();
String jsonStr = new String(Files.readAllBytes(Paths.get(fileName)));
json = new JSONObject(jsonStr);
System.out.println(json);
JSONArray jsonArray = json.getJSONArray("users");
JSONArray finalJsonArray = new JSONArray();
/**
* Get User form setNewUser method
*/
//finalJsonArray.put(setNewUserPreference());
boolean has = true;
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
finalJsonArray.put(jsonObject);
String username2 = jsonObject.getString("userName");
if (username2.equals(username)) {
has = true;
}
System.out.println("user name are :" + username2);
JSONObject jsonObject2 = jsonObject.getJSONObject("languages");
String eng = jsonObject2.getString("Eng");
String fin = jsonObject2.getString("Fin");
String ger = jsonObject2.getString("Ger");
jsonObject2.put("Eng", "ChangeEnglishValueCheckForLongValue");
System.out.println(" Eng : " + eng + " Fin " + fin + " ger : " + ger);
}
System.out.println("Final JSON Array \n" + json);
jsonArray.put(setNewUserPreference());
return json;
}
언급URL : https://stackoverflow.com/questions/11443928/how-to-modify-values-of-jsonobject-jsonarray-directly
'programing' 카테고리의 다른 글
| React 상태 비저장 구성 요소의 TypeScript 반환 유형은 무엇입니까? (0) | 2023.03.22 |
|---|---|
| PHP 경고: require_once(/var/www/html/wp-config.php): 스트림을 열지 못했습니다./var/www/html/wp-load에서 권한이 거부되었습니다.37행의 php (0) | 2023.03.22 |
| jQuery Ajax 오류 처리, 사용자 지정 예외 메시지 표시 (0) | 2023.03.17 |
| jquery를 사용하여 콘텐츠를 작은 크기의 rtl에 정렬합니다. (0) | 2023.03.17 |
| 파일 또는 어셈블리 'Newtonsoft'를 로드할 수 없습니다.Json' 또는 그 종속 요소 중 하나.매니페스트 정의가 어셈블리 참조와 일치하지 않습니다. (0) | 2023.03.17 |