有 Java 编程相关的问题?

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

您好,我需要帮助解析Java中的JSON文件

我试图使用JSON simple库解析JSON文件。前两个字符串是好的。然而,当我试图通过objectsocial解析时,我得到了facebook: nullPinterest : nullrss: null。如何解析第二个对象

这是我的JSON文件

{
    "blogURL": "www.sheriyBegin",
    "twitter": "http://twitter.com/Sherily",
    "social": {
        "facebook": "http://facebook.com/Sherily",
        "pinterest": "https://www.pinterest.com/Sherily/Sherily-articles",
        "rss": "http://feeds.feedburner.com/Sherily"
    }
}

这是我写的代码

package javaugh;

import java.io.FileReader;

import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;


public class JavaUgh {


    public static void main(String[] args)throws Exception{
        JSONParser parser = new JSONParser();

        Object obj = parser.parse(new FileReader("C:\\Users\\HP\\Desktop\\Research\\file2.txt"));
        JSONObject jsonObject = (JSONObject) obj;

        String blog = (String)jsonObject.get("blogURL");
        String twitter = (String)jsonObject.get("twitter"); 

        JSONObject jsonObject2 = (JSONObject) obj;
        String face = (String)jsonObject2.get("facebook");
        String pin = (String)jsonObject2.get("pinterest"); 
        String rss = (String)jsonObject2.get("rss"); 



        System.out.println("Blog: "+ blog);
        System.out.println("Twitter Page : " + twitter);
        System.out.println("Socail:"); 
        System.out.println("Facebook Page : " + face);
        System.out.println("Pintersect: " + pin);
        System.out.println("Rss : " + rss);


    }

}

输出:

Blog: www.sheriyBegin
Twitter Page : http://twitter.com/Sherily
Socail:
Facebook Page : null
Pintersect: null
Rss : null

共 (2) 个答案

  1. # 1 楼答案

     JSONObject social = (JSONObject) jsonObject.get("social");
     String face = (String)social.get("facebook");
     String pin = (String)social.get("pinterest"); 
     String rss = (String)social.get("rss"); 
    
  2. # 2 楼答案

    您应该从第一个json对象获得第二个json对象,而不是通过创建对第一个json对象的新引用

    JSONObject jsonObject2 = (JSONObject) jsonObject.get("social");