2016-05-31 114 views
1

我想解析下面給出的json。解析JSON文件

{ 
    "sections": [ 
    { 
     "title": "Title android", 
     "level": 1, 
     "content": [ 
     { 
      "type": "paragraph", 
      "text": "This is paragraph 1 for android." 
     } 
     { 
      "type": "paragraph", 
      "text": "This is paragraph 2 for android" 
     } 
     ], 
     "images": [ 
     { 
      "src": "http://image1 android.", 
      "caption": "Image 1." 
     }, 
     { 
      "src": "http://image2 android", 
      "caption": "Image 2." 
     } 
     ] 
    }, 
    { 
     "title": "Title java", 
     "level": 2, 
     "content": [ 
     { 
      "type": "paragraph", 
      "text": "This is paragraph 1 for Java." 
     }, 
     { 
      "type": "paragraph", 
      "text": "This is paragraph 2 for Java" 
     } 
     ], 
     "images": [ 
     { 
      "src": "http://image1 java.", 
      "caption": "Image 1." 
     }, 
     { 
      "src": "http://image2 java", 
      "caption": "Image 2." 
     } 
     ] 
    }, 
    { 
     "title": "Title json", 
     "level": 3, 
     "content": [ 
     { 
      "type": "paragraph", 
      "text": "This is paragraph 1 for Json." 
     }, 
     { 
      "type": "paragraph", 
      "text": "This is paragraph 2 for Json" 
     }, 
     { 
      "type": "paragraph", 
      "text": "This is paragraph 3 for Json" 
     } 
     ], 
     "images": [ 
     { 
      "src": "http://image1 Json.", 
      "caption": "Image 1." 
     }, 
     { 
      "src": "http://image2 Json", 
      "caption": "Image 2." 
     } 
     ] 
    } 

我想輸出這些JSON作爲

Title 1 :Title android. \n 
Content 1:This is paragraph 1 for android. 
     This is paragraph 2 for android. 
Image 1:http:// image1 android. 
Image 2:http:// image2 android. 

Title :Title Java. 
Content:This is paragraph 1 for Java. 
     This is paragraph 2 for Java. 
Image 1:http:// image1 Java. 
Image 2:http:// image2 Java. 

...等等。

我做了什麼至今

public class ParseJSON { 
    public static String[] titles; 
    public static String[] contents; 
    public static String[] levels; 

    public static final String JSON_ARRAY = "sections"; 
    public static final String TITLE = "title"; 
    public static final String CONTENT = "content"; 
    public static final String TEXT = "text"; 

    private JSONArray sections = null; 
    private JSONArray content = null; 

    private String json; 

    public ParseJSON(String json) { 
     this.json = json; 
    } 

    protected void parseJSON() { 
     JSONObject jsonObject ; 
     try { 
      jsonObject = new JSONObject(json); 
      sections = jsonObject.getJSONArray(JSON_ARRAY); 

      titles = new String[sections.length()]; 
      levels = new String[sections.length()]; 

      for (int i = 0; i < sections.length(); i++) { 
       titles[i] = sections.getJSONObject(i).getString(TITLE); 

       JSONArray content = sections.getJSONObject(i).getJSONArray(CONTENT); 
       contents = new String[content.length()]; 
       Log.d("MainActivity",contents.toString()); 
       for (int j = 0; j < content.length(); j++) { 

        contents[j] += content.getJSONObject(j).getString(TEXT).toString() + "\n\n"; 
        //Log.d("MainActivity",contents.toString()); 
       } 
      } 
     } catch (JSONException e) { 
      e.printStackTrace(); 
     } 
    } 
} 

上面的代碼是不完整的。 我想打印如上所述的json。 但我沒有得到所需的標題部分和段落部分。

當我解析從內容陣列TEXT它給所有段落從JSON組合作爲內容[0],內容[1]等。 但我想對於標題內容僅

我認爲環部起到一定的作用,但我不知道怎麼辦。

UPDATE 如果我想輸出作爲中間的一個alone.ie,

//android title part //not needed 
//The part needed is below one: 
Title :Title Java. 
Content:This is paragraph 1 for Java. 
     This is paragraph 2 for Java. 
Image 1:http:// image1 Java. 
Image 2:http:// image2 Java. 

//json title part //not needed 
+0

強烈考慮讓Java類將標題,內容和圖像放在一個對象下,而不是單獨的數組。改爲使用對象類型的數組。 –

+0

我很驚訝沒有人提到過Gson? – Eenvincible

+0

@Eenvincible你能用一個簡單的例子來幫助我解決同一個問題。謝謝 –

回答

1

使用JSON轉換器POJO工具,如this,您可以生成普通Java對象(PO​​JO),您可以用它來輕鬆地操縱您的JSON結果。

從您的JSON字符串,我能夠生成以下Java類:

public class Content { 

    @SerializedName("type") 
    @Expose 
    private String type; 
    @SerializedName("text") 
    @Expose 
    private String text; 

    /** 
    * 
    * @return 
    * The type 
    */ 
    public String getType() { 
     return type; 
    } 

    /** 
    * 
    * @param type 
    * The type 
    */ 
    public void setType(String type) { 
     this.type = type; 
    } 

    /** 
    * 
    * @return 
    * The text 
    */ 
    public String getText() { 
     return text; 
    } 

    /** 
    * 
    * @param text 
    * The text 
    */ 
    public void setText(String text) { 
     this.text = text; 
    } 

} 

那麼這代表着圖像實體:

public class Image { 

    @SerializedName("src") 
    @Expose 
    private String src; 
    @SerializedName("caption") 
    @Expose 
    private String caption; 

    /** 
    * 
    * @return 
    * The src 
    */ 
    public String getSrc() { 
     return src; 
    } 

    /** 
    * 
    * @param src 
    * The src 
    */ 
    public void setSrc(String src) { 
     this.src = src; 
    } 

    /** 
    * 
    * @return 
    * The caption 
    */ 
    public String getCaption() { 
     return caption; 
    } 

    /** 
    * 
    * @param caption 
    * The caption 
    */ 
    public void setCaption(String caption) { 
     this.caption = caption; 
    } 

} 

這是一個包含兩個對象的傘列表:

public class Section { 

    @SerializedName("title") 
    @Expose 
    private String title; 
    @SerializedName("level") 
    @Expose 
    private int level; 
    @SerializedName("content") 
    @Expose 
    private List<Content> content = new ArrayList<Content>(); 
    @SerializedName("images") 
    @Expose 
    private List<Image> images = new ArrayList<Image>(); 

    /** 
    * 
    * @return 
    * The title 
    */ 
    public String getTitle() { 
     return title; 
    } 

    /** 
    * 
    * @param title 
    * The title 
    */ 
    public void setTitle(String title) { 
     this.title = title; 
    } 

    /** 
    * 
    * @return 
    * The level 
    */ 
    public int getLevel() { 
     return level; 
    } 

    /** 
    * 
    * @param level 
    * The level 
    */ 
    public void setLevel(int level) { 
     this.level = level; 
    } 

    /** 
    * 
    * @return 
    * The content 
    */ 
    public List<Content> getContent() { 
     return content; 
    } 

    /** 
    * 
    * @param content 
    * The content 
    */ 
    public void setContent(List<Content> content) { 
     this.content = content; 
    } 

    /** 
    * 
    * @return 
    * The images 
    */ 
    public List<Image> getImages() { 
     return images; 
    } 

    /** 
    * 
    * @param images 
    * The images 
    */ 
    public void setImages(List<Image> images) { 
     this.images = images; 
    } 

} 

在生成它們並像其他任何項目一樣保存在項目中之後類,現在可以使用Gson將json字符串轉換爲具有屬性的這些對象。

既然你在你的JSON響應獲取部分List,你可以做的很簡單:

List<Section> sections = new Gson().fromJson(jsonString, Section.class); 

現在你有節,你可以遍歷獲得的圖像和內容的列表。內容,請記住,有一個自己的列表,就像圖像一樣。從那裏你應該能夠輕鬆獲得你的數據。

我希望這可以幫助你。

您可以使用Gradle添加Gson或下載jar文件並將其添加到您在android studio中的/libs文件夾中。

2

你爲什麼要折磨自己手動解析JSON?我可以推薦你使用一些輕量級的JSON解析器。這是我做的是在Android中使用org.codehaus.jackson映射器:

package yourpackage; 

import java.io.IOException; 
import java.io.StringWriter; 
import java.util.List; 

import org.codehaus.jackson.JsonGenerationException; 
import org.codehaus.jackson.JsonParseException; 
import org.codehaus.jackson.map.JsonMappingException; 
import org.codehaus.jackson.map.ObjectMapper; 

public class JsonMapper 
{ 
    private static ObjectMapper objectMapper = new ObjectMapper(); 

    public static Object fromJsonToJavaObject(String jsonObject, Class<?> clazz) throws JsonParseException, JsonMappingException, IOException 
    { 
     return objectMapper.readValue(jsonObject, clazz); 
    } 

    public static String fromJavaObjectToJson(Object javaObject) throws JsonGenerationException, JsonMappingException, IOException 
    { 
     StringWriter stringWriter = new StringWriter(); 

     objectMapper.writeValue(stringWriter, javaObject); 

     return stringWriter.toString(); 
    } 

    public static List<?> fromJsonToJavaObjects(String jsonObject, Class<?> clazz) throws JsonParseException, JsonMappingException, IOException 
    { 
     return objectMapper.readValue(jsonObject, objectMapper.getTypeFactory().constructCollectionType(List.class, clazz)); 
    } 
} 

對於你的情況,只是通過JSON字符串和期望的結果類型像TitleWithImages.class第一種方法。 這將是Maven的依賴關係(但您使用的是Android工作室):

<dependency> 
    <groupId>org.codehaus.jackson</groupId> 
    <artifactId>jackson-mapper-asl</artifactId> 
    <version>1.9.13</version> 
</dependency> 
+0

或者'new Gson()。fromJson(String,Class)'...完成相同任務的時間要短得多 –

+0

@ cricket_007前段時間,我想我在Android上使用Gson和解析時出現了內存不足的錯誤問題大量的數據。爲什麼它比我的提議'objectMapper.readValue(jsonObject,clazz);'? – Bevor

+0

定義對象映射器是另外一行代碼:)前段時間我用過Jackson,但我不確定爲什麼我切換到Gson –

3
try { 
     JSONObject jsonObject = new JSONObject(data); 
     sections = jsonObject.getJSONArray("sections"); 
     for (int i = 0; i < sections.length(); i++) { 
      JSONObject contentJSON = sections.getJSONObject(i); 
      Log.d("", "Title: "+ contentJSON.getString("level") + " " + contentJSON.getString("title")); 
      JSONArray contentArray = contentJSON.getJSONArray("content"); 
      Log.d("","Content: " + contentJSON.getString("level") + " " ); 
      for (int j = 0; j < contentArray.length(); j++) { 
       Log.d("",contentArray.getJSONObject(i).getString("text")); 
      } 
      JSONArray imageArray = contentJSON.getJSONArray("images"); 
      Log.d("","Images: " + contentJSON.getString("level") + " " ); 
      for (int j = 0; j < imageArray.length(); j++) { 
       Log.d("",imageArray.getJSONObject(j).getString("src")); 
      } 
     } 
    } catch (JSONException e) { 
     e.printStackTrace(); 
    } 

我已經印在logcat的輸出,你可以再補充它在字符串數組或更好參數創建對象,你需要

+0

我改變了不同輸出的問題。 您上面給出的答案正在工作。但是,只有我想起了這個特殊的變化。 你能否讓答案適用於那一個。 –

+0

只需將您的標題與您想要解析的部分進行比較即可。如果匹配,則解析並存儲其餘的東西。 'if(contentJSON.getString(「title」)。equals(「Title Java」))' 然後解析休息或繼續循環 –