2014-12-18 2 views
1

Android에서 HttpURLConnection에서 JSON을 파싱하려고합니다.Android - JSON을 InputStream에서 String으로 저장

{ 
"responsejson": 
    { 
     "value1": [ 
      { 
       "data": "Call", 
       "label": "Call", 
       "default": false 
      }, 
      { 
       "data": "Email", 
       "label": "Email", 
       "default": false 
      } 
     ], 
     "value2": [ 
      { 
       "attributes": { 
        "type": "Status", 
        "url": "/..." 
       }, 
       "IsOpened": false, 
       "IsDefault": true, 
       "TechLabel": "NotStarted", 
       "Id": "01Jb" 
      }, 
      { 
       "attributes": { 
        "type": "Status", 
        "url": "/..." 
       }, 
       "IsOpened": false, 
       "IsDefault": false, 
       "TechLabel": "InProgress", 
       "Id": "01Jb" 
      }, 
      { 
       "attributes": { 
        "type": "Status", 
        "url": "/..." 
       }, 
       "IsOpened": true, 
       "IsDefault": false, 
       "TechLabel": "Completed", 
       "Id": "01Jb" 
      } 
     ], 
     ... 
    } 
} 

는 내가하고 싶은, 다른 문자열에 문자열에 값 2의 내용을 내용값 1의 저장 ... 나는 데이터베이스에 저장해야하기 때문에, 그래서이다 앞으로는로드하고 파싱 할 수 있습니다. JsonReader를 사용하고 있지만 JsonReader로는이 작업을 수행 할 수 없습니다.

// ... 
inputStream = conn.getInputStream(); 
JsonReader json = new JsonReader(new InputStreamReader(in)); 
json.beginObject(); 
while (json.hasNext()) { 
    String valueName = json.nextName(); 
    // String content = ????? 
} 
json.endObject(); 
// ... 

아이디어가 있으십니까? JSON이 표시 할 값을 알 수 없기 때문에 사용자 지정 개체는이 될 수 없습니다.

+0

왜 ArrayList를 생성하고 처리를 위해 db 클래스에 전달하지 않습니까? – Paritosh

+0

@Paritosh 당신은 더 간결 할 수 있습니까? 네가 한 말 못 하겠어. – David

+0

ArrayList를 생성하십시오. 다음에 항목을 추가하십시오(). 이 ArrayList를 databaseInsertion()에 전달하십시오. 여기 ArrayList에서 항목을 가져 와서 ContentValues ​​또는 쿼리에 전달합니다. – Paritosh

답변

0

GStream을 사용하여 InputStream에서받는 JSON을 구문 분석하십시오. 그런 다음 해당 파싱 된 객체에서 ArrayList를 가져올 수 있습니다. 다시 Gson을 사용하여 arraylist를 JSON으로 다시 직렬화합니다.

-1
JSONParser parser = new JSONParser();  
List<String> output = new ArrayList<String>(); 
try { 
    Object obj = parser.parse(data); // data is JSON 
    JSONObject jsonObject = (JSONObject) obj; 
    JSONArray msg = (JSONArray) jsonObject.get("value1"); 
    JSONArray msg2 = (JSONArray) jsonObject.get("value2"); 
    Iterator<String> iterator = msg.iterator(); 
    while (iterator.hasNext()) { 
     output.add(iterator.next()); 
    } 
    String[] stringArray = output.toArray(new String[0]); 
    return stringArray; 

} catch (Exception e) { 
    return null; 
} 
+0

응답은 '파서'의 값과 유형을 설명하지 않으며 해당 정보가 없으면 쓸모가 없습니다. –

0

이 코드는 예제 json에서 작동합니다.

public class Value1 { 
    public String data,label; 
    @SerializedName("default") 
    public boolean isdefault; 
} 
public class Value2 { 
    public Attributes attributes; 
    public boolean IsOpened,IsDefault; 
    public String TechLabel,Id; 
} 
public class Attributes { 
    public String type,url; 
} 
String jsonString = "{\"responsejson\":{\"value1\":[{\"data\":\"Call\",\"label\":\"Call\",\"default\":false},{\"data\":\"Email\",\"label\":\"Email\",\"default\":false}],\"value2\":[{\"attributes\":{\"type\":\"Status\",\"url\":\"/...\"},\"IsOpened\":false,\"IsDefault\":true,\"TechLabel\":\"NotStarted\",\"Id\":\"01Jb\"},{\"attributes\":{\"type\":\"Status\",\"url\":\"/...\"},\"IsOpened\":false,\"IsDefault\":false,\"TechLabel\":\"InProgress\",\"Id\":\"01Jb\"},{\"attributes\":{\"type\":\"Status\",\"url\":\"/...\"},\"IsOpened\":true,\"IsDefault\":false,\"TechLabel\":\"Completed\",\"Id\":\"01Jb\"}]}}"; 

    try { 
     org.json.JSONObject object = new JSONObject(jsonString); 
     jsonString = object.getString("responsejson"); 
    } catch (JSONException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } 


    JsonParser parser = new JsonParser(); 
    JsonObject obj = parser.parse(jsonString).getAsJsonObject(); 
    List<Value1> list1 = new Gson().fromJson(obj.get("value1"), new TypeToken<List<Value1>>() {}.getType()); 
    List<Value2> list2 = new Gson().fromJson(obj.get("value2"), new TypeToken<List<Value2>>() {}.getType()); 
+0

JSON이 표시 할 값을 알 수 없기 때문에 사용자 정의 개체를 사용할 수 없습니다. – David

+0

당신 말이 맞아요. 위의 코드는 json 구조가 미리 알려진 경우에만 작동합니다. 나는 일반화 된 json 구조를 지원하는 새로운 대답을 작성했다. 도움이되는지 확인하십시오. – droidmad

0

json 구조를 미리 모르기 때문에 기본지도와 목록을 지원하는 GSON 2.0 기능을 사용하는 것이 가장 좋습니다.

Object object = new Gson().fromJson(jsonString, Object.class); 

생성 된 객체 (위의 예를 들어)이 같이 보이는지도 (com.google.gson.internal.LinkedTreeMap)

{responsejson입니다 : 는 역 직렬화하기 위해 다음 코드를 사용하여 기본값 = false}, value2 = [{속성 = {유형 = 상태, url =/..} = {값 1 = [{ }, IsOpened = false, IsDefault = true, TechLabel = NotStarted, Id = 01Jb}, {속성 = {유형 = 상태, url =/...}, IsOpened = 01Jb}, {속성 = {유형 = 상태, url =/...}, IsOpened = 참, IsDefault = 거짓, TechLabel = 완료, Id = 01Jb}]}}

생성 된 개체를 사용하여 구문 분석하고 db에 저장하십시오. 사용 JSON 다시 그지도를 직렬화 할 수 있습니다 :이 당신을 도와줍니다

희망. 당신은 모든 값이 지금

// to get the general object that contains all the values 
    JSONObject json = new JSONObject(json_readed); 
    JSONObject response = json.getJSONObject("responsejson"); 

    // to get the values 
    List<JSONArray> all_values = new ArrayList<JSONArray>(); 
    Iterator<?> keys = response.keys(); 

    while(keys.hasNext()){ 
     String value = (String)keys.next(); 
     if(response.get(value) instanceof JSONArray){ 
      all_values.add(response.getJSONArray(value)); 
     } 
    } 

:

1

사용이

private String convertStreamToString(InputStream is) { 
     /* 
     * To convert the InputStream to String we use the 
     * BufferedReader.readLine() method. We iterate until the 
     * BufferedReader return null which means there's no more data to 
     * read. Each line will appended to a StringBuilder and returned as 
     * String. 
     */ 
     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(); 
    } 
0

단지 정기적으로 스트림을 읽고 일반 문자열로 저장 문자열로 JSON 배열을 변환하는 데, 그 문자열을 구문 분석 (무엇이 그것의 이름 id이든간에) (all_values)라고 불리는 ArrayList에 결합됩니다.

질문에 제공 한 JSON에 시작 및 끝 부분에 "{"및 "닫기"} "대괄호가 없습니다.

+1

감사합니다. JSON 예제를 편집했습니다.) JSONObject 인스턴스 – David

0

당신이해야 할 일은 json 문자열 표현에서 JsonObject를 생성하는 것입니다.이 단계에서는 아무 것도 지정하지 않습니다.

JSONObject object = new JSONObject("json_here"); //catch all exceptions thrown. 

흥미롭게도 그 구조가 다양하다는 것을 알았습니다. 이상하게 생각합니다. 나는 당신이 다른 api 인스턴스를 당기고 있다고 생각합니다. 필요한 작업은 api 인스턴스 이름을 반환 된 json 문자열 본문에 매핑하는 pojo 클래스를 만드는 것입니다.

관심 대상 개체를 획득 한 후 GSON을 사용하는 것이 좋습니다. Java Object를 JSON으로 변환하고 역 직렬화하는 Java 직렬화/역 직렬화 라이브러리. 그런 다음, pojo 클래스를 객체로 serialize하는 것입니다. 그러면 데이터베이스에 저장됩니다. SQLite가 아닌 realm을 사용하는 것이 좋습니다.

클래스를 serialize하는 예제입니다.

class JClass { 
    private String jType; 
    private String json_body; 

    JClass() { 
    // no-args constructor 
    } 
} 

JClass j = new JClass(); 
j.jType ="some_type"; 
j.json_body = "json_body_here"; 
Gson gson = new Gson(); 
String json = gson.toJson(j); 

그런 다음 json String 객체를 가져 와서 선택한 데이터베이스에 저장하십시오.

+0

을 사용하고 object.toString()을 사용하면 반환 된 json 문자열의 본문을 그대로 유지하므로 사용자가 원하는대로 조작 할 수 있습니다. pojo 클래스의 이름을 jType으로 지정하면 db에서 다시 읽을 때 json을 구문 분석하는 방법을 알 수 있습니다. GSON은 스키마 표현처럼 저장해야합니다. pojo 클래스의 스키마를 생성하는 데에도 좋습니다. – Remario

+0

에서 json_body 매개 변수에 대한 – Remario

관련 문제