简体   繁体   English

将JSON对象解析为Java中的字符串

[英]Parse JSON object to string in java

I am a newbie to json parsing, I have grabbed a json string from a request and now I need to parse it with java. 我是json解析的新手,我从请求中获取了一个json字符串,现在我需要使用java解析它。 I'm using simple-lib for this. 我为此使用simple-lib。 But I'm really stuck as I'm not familiar with it. 但是由于我不熟悉它,所以我真的很困。 I need to extract following data 我需要提取以下数据

I used following java code for that but it's not giving me the result I need, please someone help me... 我为此使用了以下Java代码,但它没有给我所需的结果,请有人帮助我...

    JSONParser parser = new JSONParser();

    try {
        Object obj = parser.parse(new FileReader("test.json"));

        JSONObject jsonObject = (JSONObject) obj;

        JSONArray msg = (JSONArray) jsonObject.get("content");
        Iterator<String> iterator = msg.iterator();
        while(iterator.hasNext()) {
            System.out.println(iterator.next());

        }

Sample JSON 样本JSON

{
    "status": 200,
    "message": "ok",
    "timestamp": "2014-05-22T14:29:56.824+03:00",
    "pagesCount": 1,
    "version": "1.1",
    "pages": [
        {
            "number": 100,
            "subpages": [
                {
                    "number": 1,
                    "timestamp": "2014-05-22T13:41:41.116+03:00",
                    "content": "text"
                },

Something like this perhaps? 大概是这样吗?

JSONParser parser = new JSONParser();

JSONObject jsonObject = (JSONObject) parser.parse(new FileReader("test.json"));
JSONArray pages = (JSONArray) jsonObject.get("pages");
if (pages != null) {
    for (Object p : pages) {
        JSONObject page = (JSONObject) p;
        JSONArray subPages = (JSONArray) page.get("subpages");
        if  (subPages != null) {
            for (Object sp : subPages) {
                JSONObject subPage = (JSONObject) sp;
                System.err.println(subPage.get("content"));
            }
        }
    }
}

You are requesting for the value that corresponds to the key content from your outermost object, but no such key exists in your sample input. 您正在从最外面的对象请求与键content相对应的值,但样本输入中不存在这样的键。 In addition, the only field named content has a string as its value and not a JSON array. 此外,唯一的名为content字段将字符串作为其值,而不是JSON数组。

To get at the content field you would need to walk the object hierarchy until you reach the element that you need, using something along these lines: 要到达content字段,您需要使用以下几行代码来遍历对象层次结构,直到到达所需的元素:

JSONParser parser = new JSONParser();

JSONObject json = (JSONObject) parser.parse(new FileReader("test.json"));
JSONArray pages = (JSONArray) json.get("pages");

// Page 10
JSONObject page = (JSONObject) pages.get(10);

// Subpages of page 10
JSONArray subpages = (JSONArray) page.get("subpages");

// Subpage 7 of page 10
JSONObject subpage = (JSONObject) subpages.get(10);

// Content of subpage 7 of page 10
String content = (String) subpage.get("content");

Please note that I am assuming that eg index 10 corresponds to page 10. That may not be true in your case; 请注意,我假设索引10对应于第10页。 pages may not be zero-indexed, there may be missing pages or they may not be in the correct order. 页面可能没有被零索引,页面可能丢失或顺序不正确。 In that case you will have to iterate over the page and subpage lists and test the value of the number field to find the object that you need. 在这种情况下,您将必须遍历页面和子页面列表,并测试number字段的值以找到所需的对象。

In any case, if you are indeed using json-simple , as seems to be the case, then JSONObject is a subclass of HashMap and JSONArray a subclass of ArrayList . 无论如何,如果确实使用json-simple ,那么JSONObjectHashMap的子类,而JSONArrayArrayList的子类。 Therefore, their interfaces should be quite familiar to you. 因此,您对它们的界面应该非常熟悉。

Disclaimer: Untested code - exception and other error handling removed for brevity 免责声明:未经测试的代码-为简洁起见,删除了异常和其他错误处理

First of all, The json is not valid (if you pasted it complete) In JSON "{}" is an object, and "[]" is an array, others are just key value pairs. 首先,json无效(如果粘贴完整),在JSON中,“ {}”是一个对象,“ []”是一个数组,其他只是键值对。 Simply you can do like this without using parser , 简而言之,您无需使用解析器就可以这样做,

JSONObject objResponseJSON = new JSONObject(responseJSONString);
int status = (int) objResponseJSON.getInt("status");
//fetch other
JSONArray pages = objResponseJSON.getJSONArray("pages");
for(int count = 0; count < pages.length(); count++){
   //fetch other
   JSONObject objJSON = pages.getJSONObject(count);
   JSONArray subpages = objJSON.getJSONArray("subpages");
   for(int count1 = 0; count1 < subpages.length(); count1++){
      JSONObject objSubpageJSON = subpages.getJSONObject(count1);
      //fetch other
      int number = (int) objSubpageJSON.getInt("number");
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM