2016-05-31 16 views
1

Ich versuche, die unten angegebene JSON zu analysieren.JSON-Datei analysieren

{ 
    "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." 
     } 
     ] 
    } 

Ich möchte diese Json als

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. 

... und so weiter ausgeben.

Was ich

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

Der obige Code bisher getan haben, ist nicht vollständig. Ich möchte den JSON wie oben drucken. Aber ich bekomme nicht den Titel Teil und Absatz Teil wie benötigt.

Wenn ich den TEXT von Inhalt Array analysieren gibt es alle Absätze kombiniert aus dem JSON als Inhalt [0], Inhalt [1] und so weiter. Aber ich möchte Inhalte in Bezug auf Titel nur

Ich denke, der Link-Teil spielt eine Rolle, aber ich weiß nicht wie.

UPDATE Was passiert, wenn ich die Ausgabe als mittlere alone.ie wollen,

//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

Wir empfehlen dringend, eine Java-Klasse zu erstellen, die den Titel, den Inhalt und die Bilder unter einem Objekt und nicht als separate Arrays zusammenhält. Verwenden Sie stattdessen ein Array für den Objekttyp. –

+0

Ich bin überrascht, dass niemand Gson erwähnt hat? – Eenvincible

+0

@Eenvincible können Sie mir mit einem kurzen Beispiel mit gson für die gleiche Frage helfen. Danke –

Antwort

1

Mithilfe des JSON-Konverters, um Tool wie this, können Sie Plain Old Java-Objekte (POJO), die Sie verwenden können, um Ihre json-Ergebnisse zu manipulieren.

Von Ihrem json string, konnte ich die folgende Java-Klassen generieren:

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

} 

Dann ist dieses das Bild Einheit darstellt:

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

} 

Dies ist der Schirm ist, der die beiden Objekte enthält als Listen:

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

} 

Nach dem Generieren und Speichern in Ihrem Projekt wie jeder andere Klasse, können Sie jetzt Gson verwenden, um Ihre JSON-Zeichenfolge in diese Objekte mit Eigenschaften zu konvertieren.

Da Sie eine List der Abschnitte in Ihrem json Antwort erhalten, was Sie tun können, ist einfach:

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

Jetzt haben Sie eine Liste der Abschnitte, die Sie können Schleife durch Bilder und Inhalte zu erhalten. Inhalt, erinnern Sie sich, hat eine eigene Liste, genau wie Bilder. Daraus sollten Sie in der Lage sein, Ihre Daten leicht zu bekommen.

Ich hoffe, das hilft Ihnen.

Sie können Gradle verwenden, um Gson hinzuzufügen oder die JAR-Datei herunterzuladen und zu Ihrem Ordner /libs in Android Studio hinzuzufügen.

2

Warum quälst du dich von manuell JSON analysieren? Darf ich Ihnen empfehlen, einen leichten JSON-Parser zu verwenden? Dies ist, wie ich das in Android mit org.codehaus.jackson Mapper:

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

Für Ihren Fall nur die Zeichenfolge JSON übergeben und das erwartete Ergebnis Typ der ersten Methode wie TitleWithImages.class. Dies wäre der Maven-Abhängigkeit (aber Sie verwenden Android Studio):

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

Oder 'new Gson(). FromJson (String, Klasse)' ... viel kürzer, um die gleiche Aufgabe zu erfüllen –

+0

@ cricket_007 Vor einiger Zeit, ich denke, ich hatte nicht genügend Speicher Fehler auf Android bei der Verwendung von Gson und Parsing viele Daten. Und warum ist es kürzer als mein Vorschlag mit 'objectMapper.readValue (jsonObject, clazz);'? – Bevor

+0

Definieren der Objekt-Mapper ist eine weitere Codezeile :) Ich habe Jackson vor einiger Zeit verwendet, aber ich bin mir nicht sicher, warum ich zu 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(); 
    } 

ich die Ausgabe auf Logcat gedruckt haben, können Sie es nur hinzufügen, in String-Arrays oder besser erstellen Objekt mit Parametern müssen Sie

+0

Ich habe die Frage für eine andere Ausgabe geändert. Die oben angegebene Antwort funktioniert. Aber dann erinnerte ich mich nur an diese besondere Veränderung. Kannst du die Antwort auch für diese Aufgabe nutzen? –

+0

Vergleichen Sie einfach Ihren Titel mit dem Abschnitt, den Sie analysieren möchten. Wenn es übereinstimmt, dann analysiere und speichere den Rest der Dinge. 'if (contentJSON.getString (" title "). Ist gleich (" Titel Java "))' dann parse Rest oder fahre mit der Schleife fort –