programing

HTTP 응답에서 JSON 개체 가져오기

javaba 2022. 11. 5. 11:29
반응형

HTTP 응답에서 JSON 개체 가져오기

사고 싶다JSONHttp get 응답으로부터의 오브젝트:

다음은 Http get의 현재 코드입니다.

protected String doInBackground(String... params) {

    HttpClient client = new DefaultHttpClient();
    HttpGet request = new HttpGet(params[0]);
    HttpResponse response;
    String result = null;
    try {
        response = client.execute(request);         
        HttpEntity entity = response.getEntity();

        if (entity != null) {

            // A Simple JSON Response Read
            InputStream instream = entity.getContent();
            result = convertStreamToString(instream);
            // now you have the string representation of the HTML request
            System.out.println("RESPONSE: " + result);
            instream.close();
            if (response.getStatusLine().getStatusCode() == 200) {
                netState.setLogginDone(true);
            }

        }
        // Headers
        org.apache.http.Header[] headers = response.getAllHeaders();
        for (int i = 0; i < headers.length; i++) {
            System.out.println(headers[i]);
        }
    } catch (ClientProtocolException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    } catch (IOException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }
    return result;
}

convert Steam To String 함수는 다음과 같습니다.

private static String convertStreamToString(InputStream is) {

    BufferedReader reader = new BufferedReader(new InputStreamReader(is));
    StringBuilder sb = new StringBuilder();

    String line = null;
    try {
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            is.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return sb.toString();
}

지금 막 문자열 오브젝트를 받고 있어요.JSON 오브젝트를 되돌리려면 어떻게 해야 하나요?

여기서 얻을 수 있는 문자열은 JSON Object.toString()뿐입니다.즉, JSON 객체를 String 형식으로 가져옵니다.

JSON 오브젝트를 취득하는 경우는, 다음과 같이 설정할 수 있습니다.

JSONObject myObject = new JSONObject(result);

이렇게 하면 JSON을 얻을 수 있습니다.

String json = EntityUtils.toString(response.getEntity());

자세한 내용은 여기를 참조하십시오.HttpResponse에서 json을 가져옵니다.

질문에 대한 정확한 답변은 아니지만 도움이 될 수 있습니다.

public class JsonParser {

    private static DefaultHttpClient httpClient = ConnectionManager.getClient();

    public static List<Club> getNearestClubs(double lat, double lon) {
        // YOUR URL GOES HERE
        String getUrl = Constants.BASE_URL + String.format("getClosestClubs?lat=%f&lon=%f", lat, lon);

        List<Club> ret = new ArrayList<Club>();

        HttpResponse response = null;
        HttpGet getMethod = new HttpGet(getUrl);
        try {
            response = httpClient.execute(getMethod);

            // CONVERT RESPONSE TO STRING
            String result = EntityUtils.toString(response.getEntity());

            // CONVERT RESPONSE STRING TO JSON ARRAY
            JSONArray ja = new JSONArray(result);

            // ITERATE THROUGH AND RETRIEVE CLUB FIELDS
            int n = ja.length();
            for (int i = 0; i < n; i++) {
                // GET INDIVIDUAL JSON OBJECT FROM JSON ARRAY
                JSONObject jo = ja.getJSONObject(i);

                // RETRIEVE EACH JSON OBJECT'S FIELDS
                long id = jo.getLong("id");
                String name = jo.getString("name");
                String address = jo.getString("address");
                String country = jo.getString("country");
                String zip = jo.getString("zip");
                double clat = jo.getDouble("lat");
                double clon = jo.getDouble("lon");
                String url = jo.getString("url");
                String number = jo.getString("number");

                // CONVERT DATA FIELDS TO CLUB OBJECT
                Club c = new Club(id, name, address, country, zip, clat, clon, url, number);
                ret.add(c);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        // RETURN LIST OF CLUBS
        return ret;
    }

}
Again, it’s relatively straight forward, but the methods I’ll make special note of are:

JSONArray ja = new JSONArray(result);
JSONObject jo = ja.getJSONObject(i);
long id = jo.getLong("id");
String name = jo.getString("name");
double clat = jo.getDouble("lat");

정확한 JSON 출력을 보지 않고서는 작업 코드를 제공하기가 어렵습니다. 튜토리얼은 매우 유용하지만 다음과 같은 기능을 사용할 수 있습니다.

JSONObject jsonObj = new JSONObject("yourJsonString");

그런 다음 다음을 사용하여 이 json 개체에서 검색할 수 있습니다.

String value = jsonObj.getString("yourKey");

이 문제의 완전한 해결을 위해서(이 투고는 오래전에 종료된 것을 알고 있습니다).

필요한 경우JSONObject, 그 후, 우선,String에서result:

String jsonString = EntityUtils.toString(response.getEntity());

그럼 넌 네 거를 얻을 수 있어JSONObject:

JSONObject jsonObject = new JSONObject(jsonString);

를 사용해야 합니다.JSONObject다음과 같습니다.

String mJsonString = downloadFileFromInternet(urls[0]);

JSONObject jObject = null;
try {
    jObject = new JSONObject(mJsonString);
} 
catch (JSONException e) {
    e.printStackTrace();
    return false;
}

...

private String downloadFileFromInternet(String url)
{
    if(url == null /*|| url.isEmpty() == true*/)
        new IllegalArgumentException("url is empty/null");
    StringBuilder sb = new StringBuilder();
    InputStream inStream = null;
    try
    {
        url = urlEncode(url);
        URL link = new URL(url);
        inStream = link.openStream();
        int i;
        int total = 0;
        byte[] buffer = new byte[8 * 1024];
        while((i=inStream.read(buffer)) != -1)
        {
            if(total >= (1024 * 1024))
            {
                return "";
            }
            total += i;
            sb.append(new String(buffer,0,i));
        }
    }
    catch(Exception e )
    {
        e.printStackTrace();
        return null;
    }catch(OutOfMemoryError e)
    {
        e.printStackTrace();
        return null;
    }
    return sb.toString();
}

private String urlEncode(String url)
{
    if(url == null /*|| url.isEmpty() == true*/)
        return null;
    url = url.replace("[","");
    url = url.replace("]","");
    url = url.replaceAll(" ","%20");
    return url;
}

이게 도움이 되길..

문자열을 JSONObject로 변환하는 JSONObject 생성자가 있습니다.

http://developer.android.com/reference/org/json/JSONObject.html#JSONObject(java.lang.String)

api가 응답인 경우 Outputstream에서 얻은 문자열은 다음과 같은 json 문자열 형식이어야 합니다.

{\"name\":\"xyz\", \"age\":21}

이것은 여러 가지 방법으로 JSON 오브젝트로 변환할 수 있으며, 그 중 한 가지 방법은 Google GSON 라이브러리를 사용하는 것입니다. GsonBuilder builder = new GsonBuilder().setPrettyPrinting(); Gson gson = builder.create(); <javaobject> = gson.fromJson(<outputString>, <Classofobject>.class);

Json Tree Model을 구현한 Jackson을 사용하여 Gson 없이도 할 수 있습니다.

ObjectMapper mapper = new ObjectMapper();
JsonNode jsonNode = mapper.readTree(responseString);

1) String jsonString = EntityUtils.toString(response.getEntity(); 2) JSONObject jsonOject = new JSONObject(jsonString);

언급URL : https://stackoverflow.com/questions/18073849/get-a-json-object-from-a-http-response

반응형