반응형
Json 객체 Android에서 문자열 값 가져오기
저는 안드로이드는 초보입니다.프로젝트에서는 HTTP Response에서 다음 json을 얻습니다.
[{"Date":"2012-1-4T00:00:00",
"keywords":null,
"NeededString":"this is the sample string I am needed for my project",
"others":"not needed"}]
위의 json에서 "Needed String"을 받고 싶습니다.어떻게 구하지?
이게 도움이 될 거야
자바:
JSONArray arr = new JSONArray(result);
JSONObject jObj = arr.getJSONObject(0);
String date = jObj.getString("NeededString");
코틀린:
val jsonArray = JSONArray(result)
val jsonObject: JSONObject = jsonArray.getJSONObject(0)
val date= jsonObject.get("NeededString")
- get JSONObject(인덱스).위의 예에서 0은 인덱스를 나타냅니다.
넌 그냥 그 여자랑JSONArray반복하다JSONObject이 경우 JSONObject는 1개뿐이지만 더 많은 루프가 있을 수 있습니다.
JSONArray mArray;
try {
mArray = new JSONArray(responseString);
for (int i = 0; i < mArray.length(); i++) {
JSONObject mJsonObject = mArray.getJSONObject(i);
Log.d("OutPut", mJsonObject.getString("NeededString"));
}
} catch (JSONException e) {
e.printStackTrace();
}
포함하다org.json.jsonobject를 참조해 주세요.
그 후 다음을 수행할 수 있습니다.
JSONObject jresponse = new JSONObject(responseString);
responseString = jresponse.getString("NeededString");
만약,responseString는 수신한 응답을 보관합니다.
수신한 응답을 String으로 변환하는 방법을 알고 싶다면 다음과 같이 하십시오.
ByteArrayOutputStream out = new ByteArrayOutputStream();
response.getEntity().writeTo(out);
out.close();
String responseString = out.toString();
사용할 수 있습니다.getString
String name = jsonObject.getString("name");
// it will throws exception if the key you specify doesn't exist
또는optString
String name = jsonObject.optString("name");
// it will returns the empty string ("") if the key you specify doesn't exist
JSONObject 라이브러리를 사용할 수 있다면
JSONArray ja = new JSONArray("[{\"Date\":\"2012-1-4T00:00:00\",\"keywords\":null,\"NeededString\":\"this is the sample string I am needed for my project\",\"others\":\"not needed\"}]");
String result = ja.getJSONObject(0).getString("NeededString");
다음은 ResponseEntity에서 요소를 가져오는 코드입니다.
try {
final ResponseEntity<String> responseEntity = restTemplate.exchange(API_URL, HttpMethod.POST, entity, String.class);
log.info("responseEntity"+responseEntity);
final JSONObject jsonObject ;
if (responseEntity.getStatusCode() == HttpStatus.CREATED) {
try {
jsonObject = new JSONObject(responseEntity.getBody());
final String strName = jsonObject.getString("name");
log.info("name:"+strName);
} catch (JSONException e) {
throw new RuntimeException("JSONException occurred");
}
}
}catch (HttpStatusCodeException exception) {
int statusCode = exception.getStatusCode().value();
log.info("statusCode:"+statusCode);
}
여기 제가 사용한 솔루션이 있습니다. 문자열에서 JSON을 가져오는 작업입니다.
protected String getJSONFromString(String stringJSONArray) throws JSONException {
return new StringBuffer(
new JSONArray(stringJSONArray).getJSONObject(0).getString("cartype"))
.append(" ")
.append(
new JSONArray(employeeID).getJSONObject(0).getString("model"))
.toString();
}
너에게 도움이 될 것 같아
JSONArray jre = objJson.getJSONArray("Result");
for (int j = 0; j < jre.length(); j++) {
JSONObject jobject = jre.getJSONObject(j);
String date = jobject.getString("Date");
String keywords=jobject.getString("keywords");
String needed=jobject.getString("NeededString");
}
위의 답변에서 영감을 얻어 아래 답변을 봐주세요. 하지만 좀 더 자세히...
// Get The Json Response (With Try Catch)
try {
String s = null;
if (response.body() != null) {
s = response.body().string();
// Convert Response Into Json Object (With Try Catch)
JSONObject json = null;
try {
json = new JSONObject(s);
// Extract The User Id From Json Object (With Try Catch)
String stringToExtract = null;
try {
stringToExtract = json.getString("NeededString");
} catch (JSONException e) {
e.printStackTrace();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
} catch (IOException e) {
e.printStackTrace();
}
언급URL : https://stackoverflow.com/questions/8722733/getting-string-value-from-json-object-android
반응형
'programing' 카테고리의 다른 글
| Apache 프록시 뒤에 내장된 Tomcat을 사용한 Spring Boot (0) | 2023.02.26 |
|---|---|
| Wordpress 취약성 이해 (0) | 2023.02.26 |
| 각도 Ctrl 클릭? (0) | 2023.02.26 |
| WooCommerce 3에서 주문 항목과 WC_Order_Item_Product를 가져옵니다. (0) | 2023.02.26 |
| Oracle에서 Microsoft Entity Framework를 사용할 수 있습니까? (0) | 2023.02.26 |