programing

Android에서의 JSON 오브젝트 전송 및 해석

lovejava 2023. 3. 25. 09:10

Android에서의 JSON 오브젝트 전송 및 해석

서버에 JSON 오브젝트 형식의 메시지를 송신해, 서버로부터의 JSON 응답을 해석하고 싶습니다.

JSON 객체의 예

{
  "post": {
    "username": "John Doe",
    "message": "test message",
    "image": "image url",
    "time":  "current time"
  }
}

속성별로 이동하여 JSON을 수동으로 해석하려고 합니다.이 프로세스를 쉽게 하기 위해 사용할 수 있는 라이브러리/유틸리티가 있습니까?

언급되지 않은 것은 놀랍지만, json.org의 작은 패키지에 베어본(Bare Bone)을 사용하는 것이 아니라 GSon과 Jackson이 훨씬 사용하기 편리합니다.그래서:

따라서 실제로 자신의 POJO에 바인드할 수 있습니다.반쪽의 트리 노드나 리스트와 맵은 사용할 수 없습니다(적어도 잭슨은 이러한 것('실제' 오브젝트 대신 JSON, Map, List 등)에 바인드 할 수 있습니다).

2014년 3월 19일 편집:

Jackson jr 라이브러리는 Jackson과 같은 고속 스트리밍 파서/제너레이터를 사용합니다(jackson-core50kB입니다.기능은 더 제한적이지만(주석 없음, 일반 Java Bean만), 성능 면에서는 빠르고 초기화(처음 호출) 오버헤드도 매우 낮습니다.따라서 특히 소규모 애플리케이션에 적합한 선택일 수 있습니다.

org.json을 사용할 수 있습니다.JSONObject와 org.json.JSONTokener.이러한 클래스는 Android SDK와 함께 제공되므로 외부 라이브러리가 필요하지 않습니다.

데이터가 명확한 구조를 가지고 있는 경우 GSON이 가장 사용하기 쉽고, 나아가야 할 길입니다.

gson을 다운로드합니다.

참조된 라이브러리에 추가합니다.

package com.tut.JSON;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

public class SimpleJson extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        String jString = "{\"username\": \"tom\", \"message\": \"roger that\"}  ";


        GsonBuilder gsonb = new GsonBuilder();
        Gson gson = gsonb.create();
        Post pst;

        try {
            pst = gson.fromJson(jString,  Post.class);

        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
}

포스트 클래스 코드

package com.tut.JSON;

public class Post {

    String message;
    String time;
    String username;
    Bitmap icon;
}

이것은 JsonParser 클래스입니다.

public class JSONParser {

    static InputStream is = null;
    static JSONObject jObj = null;
    static String json = "";

    // constructor
    public JSONParser() {

    }

    public JSONObject getJSONFromUrl(String url) {

        // Making HTTP request
        try {
            // defaultHttpClient
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);

            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();
            is = httpEntity.getContent();

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        try {
            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();
            json = sb.toString();
        } catch (Exception e) {
            Log.e("Buffer Error", "Error converting result " + e.toString());
        }

        // try parse the string to a JSON object
        try {
            jObj = new JSONObject(json);
        } catch (JSONException e) {
            Log.e("JSON Parser", "Error parsing data " + e.toString());
        }

        // return JSON String
        return jObj;

    }

주의: DefaultHttpClient는 더 이상 sdk 23에서 지원되지 않으므로 이 코드와 함께 target sdk 21을 사용하는 것이 좋습니다.

JSON에게는 사실 아무것도 없어요.각 괄호는 키가 없는 배열(숫자로 색인화됨)을 나타냅니다.각괄호는 오브젝트(관련 배열)를 나타냅니다.Android에서 작업하는 한 SDK에 포함된 기성 클래스가 있습니다(다운로드 불필요).

다음 클래스를 확인해 주세요.http://developer.android.com/reference/org/json/package-summary.html

다른 답변들은 잭슨과 안드로이드용 인기 애드온 JSON 라이브러리인 GSON과 안드로이드에 포함된 베어본 JSON 패키지인 json.org에 주목하고 있다.

하지만 Android가 JSON API를 풀기능으로 탑재하고 있다는 점도 주목할 필요가 있다고 생각합니다.

이것은 Honeycomb: API 레벨 11에서 추가되었습니다.

은 다 같이 있다
- Android.displacc.JsonReader: 문서소스
- Android.displacc.JsonWriter: 문서소스

Jackson과 GSON에 대해 한 가지 더 생각해 보겠습니다.안드로이드보다 서드파티 라이브러리를 사용하는 것이 편리하다는 것을 알게 되었습니다.* 패키지는 제가 작성한 코드를 클라이언트와 서버 간에 공유할 수 있기 때문입니다.이는 특히 JSON과 같은 경우에 해당됩니다.JSON은 한쪽 끝에서 다른 쪽 끝으로 데이터를 전송하기 위해 JSON에 해당합니다.이러한 사용 사례의 경우 양단에서 Java를 사용하면 Android의 도입을 피할 수 있습니다.* 의존관계

아니면 관련 안드로이드를 잡을 수도 있겠죠* 소스코드를 서버 프로젝트에 추가합니다만, 아직 시도하지 않았습니다.

http://json.org에서 라이브러리(Json-lib 또는 org.json)를 다운로드하여 JSON을 해석/생성할 수 있습니다.

이것만 Import하면 됩니다.

   import org.json.JSONObject;


  constructing the String that you want to send

 JSONObject param=new JSONObject();
 JSONObject post=new JSONObject();

jsonObject를 다른 오브젝트 안에 둘 수 있기 때문에 2개의 오브젝트를 사용하고 있습니다.

post.put("username(here i write the key)","someusername"(here i put the value);
post.put("message","this is a sweet message");
post.put("image","http://localhost/someimage.jpg");
post.put("time":  "present time");

그리고 나는 이렇게 우체통을 다른 안에 넣었다.

  param.put("post",post);

이것은 내가 요청을 할 때 사용하는 방법이다.

 makeRequest(param.toString());

public JSONObject makeRequest(String param)
{
    try
    {

연결 설정

        urlConnection = new URL("your url");
        connection = (HttpURLConnection) urlConnection.openConnection();
        connection.setDoOutput(true);
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-type", "application/json;charset=UTF-8");
        connection.setReadTimeout(60000);
        connection.setConnectTimeout(60000);
        connection.connect();

출력 스트림 설정

        dataOutputStream = new DataOutputStream(connection.getOutputStream());

로그캣에서 무엇을 보내고 있는지 확인하기 위해 사용합니다.

        Log.d("OUTPUT STREAM  " ,param);
        dataOutputStream.writeBytes(param);
        dataOutputStream.flush();
        dataOutputStream.close();

        InputStream in = new BufferedInputStream(connection.getInputStream());
        BufferedReader reader = new BufferedReader(new InputStreamReader(in));
        result = new StringBuilder();
        String line;

여기서 문자열이 생성됩니다.

        while ((line = reader.readLine()) != null)
        {
            result.append(line);
        }

이 로그를 사용하여 응답 내용을 확인합니다.

         Log.d("INPUTSTREAM: ",result.toString());

서버 응답을 포함하는 문자열을 사용하여 json 설치

        jResponse=new JSONObject(result.toString());

    }
    catch (IOException e) {
        e.printStackTrace();
        return jResponse=null;
    } catch (JSONException e)
    {
        e.printStackTrace();
        return jResponse=null;
    }
    connection.disconnect();
    return jResponse;
}

만약 당신이 안드로이드에서 빠른 json 파싱을 찾고 있다면 나는 당신에게 무료로 사용할 수 있는 도구를 제안합니다.

JSON Class Creator 도구

무료로 사용할 수 있으며, 1-2초 안에 All Json 구문 분석 클래스를 만들 수 있습니다.:D

이미 GSON 이용 장려 등 이용자들의 답변이 우수하다.org.json 사용을 제안합니다.대부분의 GSON 기능이 포함되어 있습니다.또한 JSONObject에 인수로서 json 문자열을 전달할 수 있으며, 다음과 같은 처리를 합니다.

JSONObject json = new JSONObject("some random json string");

이 기능은 제가 개인적으로 가장 좋아하는 기능입니다.

json을 구문 분석하는 데 사용할 수 있는 다양한 오픈 소스 라이브러리가 있습니다.

org.json : - json을 읽거나 쓰려면 이 라이브러리를 사용할 수 있습니다.첫 번째 Json Object 생성 :-

JSONObject jsonObj = new JSONObject(<jsonStr>);

이 오브젝트를 사용하여 값을 가져옵니다.-

String id = jsonObj.getString("id");

여기서 완전한 를 볼 수 있습니다.

Jackson databind :- json을 특정 POJO 클래스로 바인드하고 해석하는 경우 잭슨 데이터 바인드라이브러리를 사용하면 json이 POJO 클래스에 바인드 됩니다.

ObjectMapper mapper = new ObjectMapper();
post= mapper.readValue(json, Post.class);

여기서 완전한 를 볼 수 있습니다.

언급URL : https://stackoverflow.com/questions/2818697/sending-and-parsing-json-objects-in-android