JSONArray를 문자열 배열로 변환
변환에 대해 질문하고 싶습니다.jsonArray에 대해서StringArray에Android여기 제 코드가 있습니다.jsonArray서버로부터.
try {
DefaultHttpClient defaultClient = new DefaultHttpClient();
HttpGet httpGetRequest = new HttpGet("http://server/android/listdir.php");
HttpResponse httpResponse = defaultClient.execute(httpGetRequest);
BufferedReader reader = new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent(),"UTF-8"));
String json = reader.readLine();
//JSONObject jsonObject = new JSONObject(json);
JSONArray jsonArray = new JSONArray(json);
Log.d("", json);
//Toast.makeText(getApplicationContext(), json, Toast.LENGTH_SHORT).show();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
그리고 이거는JSON.
[
{"name": "IMG_20130403_140457.jpg"},
{"name":"IMG_20130403_145006.jpg"},
{"name":"IMG_20130403_145112.jpg"},
{"name":"IMG_20130404_085559.jpg"},
{"name":"IMG_20130404_113700.jpg"},
{"name":"IMG_20130404_113713.jpg"},
{"name":"IMG_20130404_135706.jpg"},
{"name":"IMG_20130404_161501.jpg"},
{"name":"IMG_20130405_082413.jpg"},
{"name":"IMG_20130405_104212.jpg"},
{"name":"IMG_20130405_160524.jpg"},
{"name":"IMG_20130408_082456.jpg"},
{"name":"test.jpg"}
]
StringArray를 취득할 수 있도록 현재 사용하고 있는jsonArray를 StringArray로 변환해야 합니다.
array = {"IMG_20130403_140457.jpg","IMG_20130403_145006.jpg",........,"test.jpg"};
협조해 주셔서 감사합니다.
이 튜토리얼을 보세요.또한 위의 json을 다음과 같이 해석할 수 있습니다.
JSONArray arr = new JSONArray(yourJSONresponse);
List<String> list = new ArrayList<String>();
for(int i = 0; i < arr.length(); i++){
list.add(arr.getJSONObject(i).getString("name"));
}
가장 간단하고 올바른 코드는 다음과 같습니다.
public static String[] toStringArray(JSONArray array) {
if(array==null)
return new String[0];
String[] arr=new String[array.length()];
for(int i=0; i<arr.length; i++) {
arr[i]=array.optString(i);
}
return arr;
}
사용.List<String>배열의 길이를 알고 계시기 때문에 권장하지 않습니다.사용하는 것에 주의해 주세요.arr.length에for메서드 호출을 회피하는 조건, 즉,array.length(), 각 루프에 있습니다.
public static String[] getStringArray(JSONArray jsonArray) {
String[] stringArray = null;
if (jsonArray != null) {
int length = jsonArray.length();
stringArray = new String[length];
for (int i = 0; i < length; i++) {
stringArray[i] = jsonArray.optString(i);
}
}
return stringArray;
}
끔찍한 해킹:
String[] arr = jsonArray.toString().replace("},{", " ,").split(" ");
루프를 통해 문자열을 생성할 수 있습니다.
List<String> list = new ArrayList<String>();
for (int i=0; i<jsonArray.length(); i++) {
list.add( jsonArray.getString(i) );
}
String[] stringArray = list.toArray(new String[list.size()]);
같은 시나리오 중 하나를 시도했지만 JSONAray를 목록으로 변환하기 위한 다른 간단한 솔루션을 찾았습니다.
import java.lang.reflect.Type;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
String jsonStringArray = "[\"JSON\",\"To\",\"Java\"]";
//creating Gson instance to convert JSON array to Java array
Gson converter = new Gson();
Type type = new TypeToken<List<String>>(){}.getType();
List<String> list = converter.fromJson(jsonStringArray, type );
시험해 보다
코드는 다음과 같습니다.
// XXX satisfies only with this particular string format
String s = "[{\"name\":\"IMG_20130403_140457.jpg\"},{\"name\":\"IMG_20130403_145006.jpg\"},{\"name\":\"IMG_20130403_145112.jpg\"},{\"name\":\"IMG_20130404_085559.jpg\"},{\"name\":\"IMG_20130404_113700.jpg\"},{\"name\":\"IMG_20130404_113713.jpg\"},{\"name\":\"IMG_20130404_135706.jpg\"},{\"name\":\"IMG_20130404_161501.jpg\"},{\"name\":\"IMG_20130405_082413.jpg\"},{\"name\":\"IMG_20130405_104212.jpg\"},{\"name\":\"IMG_20130405_160524.jpg\"},{\"name\":\"IMG_20130408_082456.jpg\"},{\"name\":\"test.jpg\"}]";
s = s.replace("[", "").replace("]", "");
s = s.substring(1, s.length() - 1);
String[] split = s.split("[}][,][{]");
for (String string : split) {
System.out.println(string);
}
여기 있습니다.
String tempNames = jsonObj.names().toString();
String[] types = tempNames.substring(1, tempNames.length()-1).split(","); //remove [ and ] , then split by ','
휴대용 Java API만 사용합니다.http://www.oracle.com/technetwork/articles/java/json-1973242.html
try (JsonReader reader = Json.createReader(new StringReader(yourJSONresponse))) {
JsonArray arr = reader.readArray();
List<String> l = arr.getValuesAs(JsonObject.class)
.stream().map(o -> o.getString("name")).collect(Collectors.toList());
}
바로 사용할 수 있는 방법:
/**
* Convert JSONArray to ArrayList<String>.
*
* @param jsonArray JSON array.
* @return String array.
*/
public static ArrayList<String> toStringArrayList(JSONArray jsonArray) {
ArrayList<String> stringArray = new ArrayList<String>();
int arrayIndex;
JSONObject jsonArrayItem;
String jsonArrayItemKey;
for (
arrayIndex = 0;
arrayIndex < jsonArray.length();
arrayIndex++) {
try {
jsonArrayItem =
jsonArray.getJSONObject(
arrayIndex);
jsonArrayItemKey =
jsonArrayItem.getString(
"name");
stringArray.add(
jsonArrayItemKey);
} catch (JSONException e) {
e.printStackTrace();
}
}
return stringArray;
}
답변이 늦었지만 Gson을 사용하여 생각해낸 것은 다음과 같습니다.
jsonarray foo의 경우: [{"test": "bar", {"test": "bar2"}]
JsonArray foo = getJsonFromWherever();
String[] test = new String[foo.size()]
foo.forEach(x -> {test = ArrayUtils.add(test, x.get("test").getAsString());});
또, 복수의 어레이를 변환 및 Marge 할 수 있는 솔루션을 다음에 나타냅니다.
public static String[] multiJsonArrayToSingleStringArray(JSONArray... arrays) {
ArrayList<String> list=new ArrayList<>();
for (JSONArray array : arrays)
for (int i = 0; i < array.length(); i++)
list.add(array.optString(i));
return list.toArray(new String[list.size()]);
}
늦은 거 알아요누군가에게 도움이 되었으면 좋겠어요.
문자열 배열이 있는 경우.이런 말을 하다
String chars = "["a","b","c"]";// Json stringfied string
List<String>charArray = (List<String>) JSON.parse(chars);
String[] stringArray = cars.toArray(new String[char.size()]);
여기 있습니다. 어레이에는 다음과 같은 것이 있습니다.
stringarray = ["a","b","c"];
이 함수에 json 배열을 입력하면 문자열 배열로 출력됩니다.
입력 예 - { "성별" : ["남성", "여성"] }
출력 - {"남성", "여성"}
private String[] convertToStringArray(Object array) throws Exception {
return StringUtils.stripAll(array.toString().substring(1, array.toString().length()-1).split(","));
}
다음 코드는 다음 형식의 JSON 어레이를 변환합니다.
[{"version":70.3.0;3", {"version":6R_16B000I_J4;3", {"version":46.3.0;3", {"version":20.3.0;2", {"{"version":4.1.3;0", {"}]
문자열 목록으로
[70.3.0;3, 6R_16B000I_J4;3, 46.3.0;3, 20.3.0;2, 4.1.3;0, 10.3.0;1]
코드:
ObjectMapper mapper = new ObjectMapper(); ArrayNode node = (ArrayNode)mapper.readTree(dataFromDb); data = node.findValuesAsText("version");// "version"은 JSON의 노드입니다.
com.sysml.syslog.syslogind를 사용합니다.오브젝트 맵퍼
여기 좀 봐주세요.JSONArray.toList()이 경우 a가 반환됩니다.ListJSON 구조를 나타내는 Maps and Lists가 포함되어 있습니다.Java Stream에서 다음과 같이 사용할 수 있습니다.
JSONArray array = new JSONArray(jsonString);
List<String> result = array.toList().stream()
.filter(Map.class::isInstance)
.map(Map.class::cast)
.map(o -> o.get("name"))
.filter(String.class::isInstance)
.map(String.class::cast)
.collect(Collectors.toList());
이는 더 복잡한 개체에도 유용할 수 있습니다.
다른 방법으로는,IntStream해서 JSONArray.
JSONArray array = new JSONArray(jsonString);
List<String> result = IntStream.range(0, array.length())
.mapToObj(array::getJSONObject)
.map(o -> o.getString("name"))
.collect(Collectors.toList());
답변자가 도움을 줬지만 충분치 않았던 질문에 대한 답변을 여기에 올립니다.
이것은 을 ,, 것, son, son, mission, mission, mission, mission, mission, mission, mission, mission, mission, mission, mission, mission, mission, mission, mission, mission, mission, mission, mission, mission, , mission, missionString[]jsonsimple을 사용합니다.
(대단한) 디코딩 예시와 문서에 따르면 JSONAray는 java List이므로 List 메서드에 액세스할 수 있습니다.
R&A」 「R&A」 「R&A」로 할 수 ?String[]다음을 포함합니다.
JSONObject assemblingTags = (JSONObject) obj.get("assembling-tags");
JSONArray aTagsList = (JSONArray) assemblingTags.get("list");
String[] tagsList = (String[]) aTagsList.stream().toArray(String[]::new);
다음 코드는 JSON 어레이를 목록으로 변환합니다.
예를 들어,
import org.json.JSONArray
String data = "YOUR_JSON_ARRAY_DATA";
JSONArray arr = new JSONArray(data);
List<String> list = arr.toList().stream().map(Object::toString).collect(Collectors.toList());
언급URL : https://stackoverflow.com/questions/15871309/convert-jsonarray-to-string-array
'programing' 카테고리의 다른 글
| Oracle에서 대소문자를 구분하지 않는 검색 (0) | 2023.03.12 |
|---|---|
| 테이블 이름 주위의 따옴표는 정확히 어떤 역할을 합니까? (0) | 2023.03.12 |
| 우코머스의 변주곡 (0) | 2023.03.12 |
| AngularJ: ng-click과 조합하여 동작하지 않는 경우? (0) | 2023.03.12 |
| Oracle에서 예약어를 피하려면 어떻게 해야 합니까? (0) | 2023.03.12 |