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

时间:2016-06-27 02:42:27

标签: java json

我正在尝试使用库JSON简单解析JSON文件。前两个字符串很好。但是,当我尝试通过对象社交进行解析时,我得到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 个答案:

答案 0 :(得分:1)

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

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

答案 1 :(得分:0)

 JSONObject social = (JSONObject) jsonObject.get("social");
 String face = (String)social.get("facebook");
 String pin = (String)social.get("pinterest"); 
 String rss = (String)social.get("rss"); 
相关问题