Java 解析JSON文件

Java 解析JSON文件,java,android,json,parsing,Java,Android,Json,Parsing,我试图解析下面给定的json { "sections": [ { "title": "Title android", "level": 1, "content": [ { "type": "paragraph", "text": "This is paragraph 1 for android." } { "type": "paragraph

我试图解析下面给定的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来折磨自己?我建议您使用一些轻量级JSON解析器。这就是我在安卓系统中使用
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));
    }
}

为什么要手动解析JSON来折磨自己?我建议您使用一些轻量级JSON解析器。这就是我在安卓系统中使用
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));
    }
}
试试看{
JSONObject JSONObject=新的JSONObject(数据);
sections=jsonObject.getJSONArray(“sections”);
对于(int i=0;i
我已经在Logcat上打印了输出,您可以将其添加到字符串数组中,或者更好地使用所需的参数创建对象{ JSONObject JSONObject=新的JSONObject(数据); sections=jsonObject.getJSONArray(“sections”); 对于(int i=0;i
我已经在Logcat上打印了输出,您可以将其添加到字符串数组中,或者更好地使用json converter to pojo工具创建带有所需参数的对象,例如,您可以生成普通的旧Java对象(pojo),您可以使用它轻松地操作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;
   }

}
现在,您有了一个可以循环获取图像和内容的部分列表。记住,内容有自己的列表,就像图像一样。因此,您应该能够轻松获取数据

我希望这对你有帮助


您可以使用Gradle添加Gson或下载jar文件,并将其添加到android studio中的
/libs
文件夹中。

使用json converter to pojo工具,您可以生成简单的旧Java对象(pojo),您可以使用它轻松地操作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;
   }

}
现在,您有了一个可以循环获取图像和内容的部分列表。记住,内容有自己的列表,就像图像一样。因此,您应该能够轻松获取数据

我希望这对你有帮助


您可以使用Gradle添加Gson或下载jar文件,并将其添加到android studio中的
/libs
文件夹中。

新建Gson()。。。完成同样的任务要短得多task@cricket_007不久前,我想我在Android上使用Gson解析大量数据时遇到了内存不足的错误问题。为什么它比我关于
objectMapper.readValue(jsonObject,clazz)的建议要短?定义对象映射器是另一行代码:)我不久前确实使用过Jackson,但我不确定为什么要切换到Gson@Bevor . 谢谢你的回答。但我没有使用杰克逊或格森的经验。我不理解“预期结果类型”。类中应该有什么?@AlexanderTheGreat最终会将结果传递给java对象,对吗?因此,您需要定义这个类,让我们使用
Section
对象列表将其称为
Sections
。这些
部分
对象具有
标题
级别
等属性以及
内容
对象列表。这些对象具有
类型
文本
属性。与
图像相同
。所有属性都必须有getter和setter.Or
new Gson().fromJson(字符串,类)
。。。完成同样的任务要短得多task@cricket_007不久前,我想我在Android上使用Gson解析大量数据时遇到了内存不足的错误问题。为什么它比我关于
objectMapper.readValue(jsonObject,clazz)的建议要短?定义对象映射器是另一行代码:)我不久前确实使用过Jackson,但我不确定为什么要切换到Gson@Bevor . 谢谢你的回答。但我没有使用杰克逊或格森的经验。我不理解“预期结果类型”。课堂上应该有什么?@Alexa