有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java解析JSON文件

我试图解析下面给定的json

{
  "sections": [
    {
      "title": "Title 安卓",
      "level": 1,
      "content": [
        {
          "type": "paragraph",
          "text": "This is paragraph 1 for 安卓."
        }
        {
          "type": "paragraph",
          "text": "This is paragraph 2 for 安卓"
        }
      ],
      "images": [
        {
          "src": "http://image1 安卓.",
          "caption": "Image 1."
        },
        {
          "src": "http://image2 安卓",
          "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 安卓. \n
Content 1:This is paragraph 1 for 安卓.
        This is paragraph 2 for 安卓.
Image 1:http:// image1 安卓.
Image 2:http:// image2 安卓.

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。 但我没有得到标题部分和段落部分的需要

当我解析content数组中的文本时,它将json中的所有段落组合为content[0]、content[1]等等。 但我只想要标题方面的内容

我认为链接部分发挥了一些作用,但我不知道如何发挥作用

更新 如果我想把输出单独作为中间的一个呢。即

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

共 (3) 个答案

  1. # 1 楼答案

    使用像this这样的json转换为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;
       }
    
    }
    

    在生成它们并像任何其他类一样保存在项目中之后,现在可以使用Gson将json字符串转换为这些具有属性的对象

    由于您在json响应中获得了List个节,所以您可以做的很简单:

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

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

    我希望这对你有帮助

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

  2. # 2 楼答案

    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上打印了输出,您可以将其添加到字符串数组中,或者更好地使用所需的参数创建对象

  3. # 3 楼答案

    为什么要手动解析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 studio):

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