웹개발/Java & Jsp
[Java] String/Json 객체 to JSONArray
kmhan
2021. 12. 8. 17:45
728x90
반응형
1. String to JSONArray
POST 파라미터 전송
|
1
2
3
|
{
"exam" : "[{\"testNum\": 1, \"testStr\": "A"}, {\"testNum\": 2, \"testStr\": "B"}]"
}
|
cs |
Java 소스
- 단일 객체는 JSONObject로, 복수 객체는 JSONArray로 변경
|
1
2
3
4
5
6
7
8
9
10
11
12
|
JSONParser jsonParser = new JSONParser();
JSONArray jsonArray = new JSONArray();
JSONObject obj = new JSONObject();
int testNum;
String testStr;
jsonArray = (JSONArray) jsonParser.parse(pUser.get("exam"));
for(int i=0; i<jsonArray.size(); i++) {
obj = (JSONObject) jsonArray.get(i);
int testNum = Integer.parseInt(obj.get("testNum").toString());
String testStr = obj.get("testStr").toString();
}
|
cs |
2. Json 객체 to JSONArray
POST 파라미터 전송
|
1
2
3
4
5
6
7
8
9
10
11
12
13
|
{
"exam" : [
{
"testNum": 1,
"testStr": "A"
},
{
"testNum": 2,
"testStr": "B"
}
]
}
|
cs |
Java 소스
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
JSONParser jsonParser = new JSONParser();
JSONArray jsonArray = new JSONArray();
JSONObject obj = new JSONObject();
ObjectMapper mapper = new ObjectMapper();
String jsonString;
int testNum;
String testStr;
jsonString = mapper.writeValueAsString(pUser.get("exam"));
jsonArray = (JSONArray) jsonParser.parse(jsonString);
for(int i=0; i<jsonArray.size(); i++) {
obj = (JSONObject) jsonArray.get(i);
int testNum = Integer.parseInt(obj.get("testNum").toString());
String testStr = obj.get("testStr").toString();
}
|
cs |
728x90
반응형