어레이 이름 없이 JSONArray를 가져오시겠습니까?
JSON은 처음이라서 튜토리얼 http://p-xr.com/android-tutorial-how-to-parse-read-json-data-into-a-android-listview/ #http://http://p-xr.com/android-tutorial-how-to-parse-read-json-data-into-a-android-listview/ 를 사용해 봅니다.
JSON, C언어, Java, Android는 처음이지만 배우고 있습니다.튜토리얼에서는 명명된 배열이라고 부르는 것을 사용하지만 안드로이드 프로젝트에서 사용하는 모든 JSON은 명명된 배열이 없는 단순한 테이블 행을 사용합니다.사용하고 있는 JSON과 튜토리얼의 지진 json의 예를 다음에 나타냅니다.
튜토리얼은 지진 어레이를 반복하여 다음 코드를 사용하여 JAVA 해시맵 목록으로 변환합니다.
JSONArray earthquakes = json.getJSONArray("earthquakes");
for(int i=0;i<earthquakes.length();i++){
HashMap<String, String> map = new HashMap<String, String>();
JSONObject e = earthquakes.getJSONObject(i);
map.put("id", String.valueOf(i));
map.put("name", "Earthquake name:" + e.getString("eqid"));
map.put("magnitude", "Magnitude: " + e.getString("magnitude"));
mylist.add(map);
}
질문입니다. 어떻게 하면json.getJSONArray("")
제 JSON이 아래와 같이 단순하다면요?나머지 코드를 변환할 수 있습니다.JSON을 로드하는 방법만 알면 됩니다.getJSONArray("strJsonArrayName")
이 없으면strJsonArrayName
.
My JSON(이름 없는 어레이)
[
{
"cnt":1,
"name":"American",
"pk":7
},
{
"cnt":2,
"name":"Celebrities",
"pk":3
},
{
"cnt":1,
"name":"Female",
"pk":2
},
{
"cnt":1,
"name":"Language",
"pk":8
},
{
"cnt":1,
"name":"Male",
"pk":1
},
{
"cnt":1,
"name":"Region",
"pk":9
}
]
튜토리얼의 JSON(네임드 어레이)
{
"earthquakes":[
{
"eqid":"c0001xgp",
"magnitude":8.8,
"lng":142.369,
"src":"us",
"datetime":"2011-03-11 04:46:23",
"depth":24.4,
"lat":38.322
},
{
"eqid":"c000905e",
"magnitude":8.6,
"lng":93.0632,
"src":"us",
"datetime":"2012-04-11 06:38:37",
"depth":22.9,
"lat":2.311
},
{
"eqid":"2007hear",
"magnitude":8.4,
"lng":101.3815,
"src":"us",
"datetime":"2007-09-12 09:10:26",
"depth":30,
"lat":-4.5172
},
{
"eqid":"c00090da",
"magnitude":8.2,
"lng":92.4522,
"src":"us",
"datetime":"2012-04-11 08:43:09",
"depth":16.4,
"lat":0.7731
},
{
"eqid":"2007aqbk",
"magnitude":8,
"lng":156.9567,
"src":"us",
"datetime":"2007-04-01 18:39:56",
"depth":10,
"lat":-8.4528
},
{
"eqid":"2007hec6",
"magnitude":7.8,
"lng":100.9638,
"src":"us",
"datetime":"2007-09-12 21:49:01",
"depth":10,
"lat":-2.5265
},
{
"eqid":"a00043nx",
"magnitude":7.7,
"lng":100.1139,
"src":"us",
"datetime":"2010-10-25 12:42:22",
"depth":20.6,
"lat":-3.4841
},
{
"eqid":"2010utc5",
"magnitude":7.7,
"lng":97.1315,
"src":"us",
"datetime":"2010-04-06 20:15:02",
"depth":31,
"lat":2.3602
},
{
"eqid":"2009mebz",
"magnitude":7.6,
"lng":99.9606,
"src":"us",
"datetime":"2009-09-30 08:16:09",
"depth":80,
"lat":-0.7889
},
{
"eqid":"2009kdb2",
"magnitude":7.6,
"lng":92.9226,
"src":"us",
"datetime":"2009-08-10 17:55:39",
"depth":33.1,
"lat":14.0129
}
]
}
튜토리얼에서는 @M д б 、 @Cody Caughlan 님의 답변을 바탕으로 JSONFunctions.get JSONFromURL을 JSONOBject가 아닌 JSONArray로 포맷할 수 있었습니다.여기 작업 코드가 수정되었습니다. 감사합니다!
public class JSONfunctions {
public static JSONArray getJSONfromURL(String url){
InputStream is = null;
String result = "";
JSONArray jArray = null;
HttpClient httpclient = new DefaultHttpClient();
HttpGet httpget = new HttpGet(url);
HttpResponse response = httpclient.execute(httpget);
HttpEntity entity = response.getEntity();
is = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result=sb.toString();
jArray = new JSONArray(result);
return jArray;
}
}
전화 안 해도 돼json.getJSONArray()
이미 사용하고 있는 JSON은 어레이이기 때문입니다.그러니까, 예를 들면JSONObject
; 를 사용합니다.JSONArray
이것으로 충분합니다.
// ...
JSONArray json = new JSONArray(result);
// ...
for(int i=0;i<json.length();i++){
HashMap<String, String> map = new HashMap<String, String>();
JSONObject e = json.getJSONObject(i);
map.put("id", String.valueOf(i));
map.put("name", "Earthquake name:" + e.getString("eqid"));
map.put("magnitude", "Magnitude: " + e.getString("magnitude"));
mylist.add(map);
}
취급하는 JSON을 다음 명령어로 해석해야 하기 때문에 튜토리얼과 완전히 동일한 방법을 사용할 수 없습니다.JSONArray
근본적으로는 가 아니라JSONObject
.
JSONArray
컨스트럭터를 가지고 있습니다.String
source(어레이로 간주)
그러니까 이런 거
JSONArray array = new JSONArray(yourJSONArrayAsString);
이름 붙여진 JSONArray가 JSONObject라고 가정하고 서버에서 데이터에 액세스하여 Android GridView를 채웁니다.제 방법은 다음과 같습니다.
private String[] fillTable( JSONObject jsonObject ) {
String[] dummyData = new String[] {"1", "2", "3", "4", "5", "6", "7","1", "2", "3", "4", "5", "6", "7","1", "2", "3", "4", "5", "6", "7", };
if( jsonObject != null ) {
ArrayList<String> data = new ArrayList<String>();
try {
// jsonArray looks like { "everything" : [{}, {},] }
JSONArray jsonArray = jsonObject.getJSONArray( "everything" );
int number = jsonArray.length(); //How many rows have got from the database?
Log.i( Constants.INFORMATION, "Number of ows returned: " + Integer.toString( number ) );
// Array elements look like this
//{"success":1,"error":0,"name":"English One","owner":"Tutor","description":"Initial Alert","posted":"2013-08-09 15:35:40"}
for( int element = 0; element < number; element++ ) { //visit each element
JSONObject jsonObject_local = jsonArray.getJSONObject( element );
// Overkill on the error/success checking
Log.e("JSON SUCCESS", Integer.toString( jsonObject_local.getInt(Constants.KEY_SUCCESS) ) );
Log.e("JSON ERROR", Integer.toString( jsonObject_local.getInt(Constants.KEY_ERROR) ) );
if ( jsonObject_local.getInt( Constants.KEY_SUCCESS) == Constants.JSON_SUCCESS ) {
String name = jsonObject_local.getString( Constants.KEY_NAME );
data.add( name );
String owner = jsonObject_local.getString( Constants.KEY_OWNER );
data.add( owner );
String description = jsonObject_local.getString( Constants.KEY_DESCRIPTION );
Log.i( "DESCRIPTION", description );
data.add( description );
String date = jsonObject_local.getString( Constants.KEY_DATE );
data.add( date );
}
else {
for( int i = 0; i < 4; i++ ) {
data.add( "ERROR" );
}
}
}
} //JSON object is null
catch ( JSONException jsone) {
Log.e( "JSON EXCEPTION", jsone.getMessage() );
}
dummyData = data.toArray( dummyData );
}
return dummyData;
}
19API lvl 미만의 솔루션은 다음과 같습니다.
일단은.Gson obj를 만듭니다. -->
Gson gson = new Gson();
두 번째 단계는 (JsonObjectRequest가 아닌) StringRequest를 사용하여 jsonObj를 문자열로 가져오는 것입니다.
- JsonArray를 얻기 위한 마지막 단계...
YoursObjArray[] yoursObjArray = gson.fromJson(response, YoursObjArray[].class);
언급URL : https://stackoverflow.com/questions/10164741/get-jsonarray-without-array-name
'programing' 카테고리의 다른 글
콜백에 추가 파라미터 전달 (0) | 2023.03.18 |
---|---|
데이터 소스 없이 스프링 부트 응용 프로그램 (0) | 2023.03.18 |
jq - 오브젝트의 부모 값을 인쇄하려면 어떻게 해야 합니까? (0) | 2023.03.18 |
Vagrant에서 호스트와 게스트 간의 동기화 지연 시간 단축(NFS 동기화 폴더) (0) | 2023.03.18 |
AngularJS는 이력 상태를 푸시하지 않고 리다이렉트한다. (0) | 2023.03.18 |