IT박스

Android에서 JSON 객체 전송 및 구문 분석

itboxs 2020. 6. 23. 07:57
반응형

Android에서 JSON 객체 전송 및 구문 분석


JSON 객체 형식의 메시지를 서버에 보내고 서버의 JSON 응답을 구문 분석하고 싶습니다.

JSON 객체의 예

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

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


나는 이것이 언급되지 않은 것에 놀랐습니다 : json.org의 작은 패키지로 베어 본 대신 수동 프로세스를 사용하는 대신 GSon과 Jackson이 사용하기가 훨씬 편리합니다. 그래서:

따라서 일부 반 트리 트리 노드 또는 목록 및 맵이 아닌 자신의 POJO에 실제로 바인딩 할 수 있습니다. (그리고 Jackson은 적어도 실제 객체 대신에 이것을 원한다면 JsonNode, Map, List와 같은 것들에 바인딩 할 수 있습니다.

2014 년 3 월 19 일 수정 :

또 다른 새로운 경쟁자는 Jackson jr 라이브러리입니다. Jackson 과 같은 빠른 스트리밍 파서 / 제너레이터를 사용 jackson-core하지만 데이터 바인딩 부분은 작습니다 (50kB). 기능은 더 제한적이지만 (주석이없고 일반적인 Java Bean) 성능이 빠르며 초기화 (처음 호출) 오버 헤드도 매우 낮아야합니다. 따라서 특히 작은 응용 프로그램의 경우 좋은 선택 일 수 있습니다.


org.json.JSONObjectorg.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;

    }

Note: DefaultHttpClient is no longer supported by sdk 23, so it is advisable to use target sdk 21 with this code.


There's not really anything to JSON. Curly brackets are for "objects" (associative arrays) and square brackets are for arrays without keys (numerically indexed). As far as working with it in Android, there are ready made classes for that included in the sdk (no download required).

Check out these classes: http://developer.android.com/reference/org/json/package-summary.html


Other answers have noted Jackson and GSON - the popular add-on JSON libraries for Android, and json.org, the bare-bones JSON package that is included in Android.

But I think it is also worth noting that Android now has its own full featured JSON API.

This was added in Honeycomb: API level 11.

This comprises
- android.util.JsonReader: docs, and source
- android.util.JsonWriter: docs, and source

I will also add one additional consideration that pushes me back towards Jackson and GSON: I have found it useful to use 3rd party libraries rather then android.* packages because then the code I write can be shared between client and server. This is particularly relevant for something like JSON, where you might want to serialize data to JSON on one end for sending to the other end. For use cases like that, if you use Java on both ends it helps to avoid introducing android.* dependencies.

Or I guess one could grab the relevant android.* source code and add it to your server project, but I haven't tried that...


You can download a library from http://json.org (Json-lib or org.json) and use it to parse/generate the JSON


you just need to import this

   import org.json.JSONObject;


  constructing the String that you want to send

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

im using two object because you can have an jsonObject within another

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");

then i put the post json inside another like this

  param.put("post",post);

this is the method that i use to make a request

 makeRequest(param.toString());

public JSONObject makeRequest(String param)
{
    try
    {

setting the connection

        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();

setting the outputstream

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

i use this to see in the logcat what i am sending

        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;

here the string is constructed

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

i use this log to see what its comming in the response

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

instancing a json with the String that contains the server response

        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;
}

if your are looking for fast json parsing in android than i suggest you a tool which is freely available.

JSON Class Creator tool

It's free to use and it's create your all json parsing class within a one-two seconds.. :D


Although there are already excellent answers are provided by users such as encouraging use of GSON etc. I would like to suggest use of org.json. It includes most of GSON functionalities. It also allows you to pass json string as an argument to it's JSONObject and it will take care of rest e.g:

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

This functionality make it my personal favorite.


There are different open source libraries, which you can use for parsing json.

org.json :- If you want to read or write json then you can use this library. First create JsonObject :-

JSONObject jsonObj = new JSONObject(<jsonStr>);

Now, use this object to get your values :-

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

You can see complete example here

Jackson databind :- If you want to bind and parse your json to particular POJO class, then you can use jackson-databind library, this will bind your json to POJO class :-

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

You can see complete example here

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

반응형