코린이

 

{
	"template": {
		"outputs": [{
			"carousel": {
				"type": "listCard",
				"items": [{
					"items": [{
						"title": "title",
						"action": "message",
						"imageUrl": "img",
						"description": "description",
						"messageText": "message"
					}],
					"header": {
						"title": "bitTitle"
					}
				}]
			}
		}]
	},
	"version": "2.0"
}

이런 json이 있을 때, 나는 "outputs"밑에 simpleText를 넣고싶었다. 

일단 build.gradle

implementation group: 'com.googlecode.json-simple', name: 'json-simple', version: '1.1.1'

> json-simple 은 내부적으로 json을 처리하기위해 map, list를 사용함.

JSONParser parser = new JSONParser(); 
// 데이터를 json으로 파싱
JSONObject responseMessage = (JSONObject) parser.parse(json);

//json으로 파싱된 객체에 template라는 key 찾기
JSONObject template = (JSONObject) responseMessage.get("template");
그 template 안에 있는 outputs이라는 key 찾기
JSONArray outputs = (JSONArray) template.get("outputs");

//map형태로 json key, value 작성
JSONObject simpleText = new JSONObject();
simpleText.put("text", "삽입할 text");

JSONObject newTextObject = new JSONObject();
newTextObject.put("simpleText", simpleText);

// 새로운 객체를 outputs 배열에 추가
outputs.add(newTextObject);

// 변화된 responseMessage를 다시 JSON으로 변환
String updatedJson = responseMessage.toJSONString();
System.out.println(updatedJson);

이렇게 하면 json안에 map이 들어감! 사실 map이 들어갔다는 느낌보다 map처럼 만든 json이 들어간거임!

반응형
profile

코린이

@코인아님

포스팅이 좋았다면 "좋아요❤️" 또는 "구독👍🏻" 해주세요!