{"success":"0000","status":"100","result":{"code":"00","msg":"22"}} 형태의 json에서 code와 msg를 분리하고 싶다.
//example.
String jsonString = "{"success":"0000","status":"100","result":{"code":"00","msg":"22"}}
";
JSONObject jObject = new JSONObject(jsonString);
String resultObj = jObject.getString("result");
String code = jObject.getJSONObject("result").getString("code");
=> 00 출력
import lombok.*;
@Getter
@Setter
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class TestDto {
private String success;
private String status;
private resultGroup result;
@Override
public String toString() {
return success;
}
}
@RestController
public class TestController {
@GetMapping("/test111")
public String getExceptionTest123 () throws JSONException {
TestDto testObj= new TestDto().builder()
.success("0000")
.status("100")
.result(resultGroup.builder().code("00").msg("22").build())
.build();
System.out.println(testObj);
GsonBuilder builder = new GsonBuilder();
builder.serializeNulls();
Gson gson = builder.create();
String jsonString = gson.toJson(testObj);
System.out.println(jsonString);
JSONObject jObject = new JSONObject(jsonString);
String resultObj = jObject.getString("result");
String code = jObject.getJSONObject("result").getString("code");
System.out.println(code);
return resultObj;
}