如何在java中读取json文件

时间:2017-09-20 12:28:23

标签: java json

我想阅读Json文件。我的Json文件包含以下内容

[
  {
    "arguments" : [
      {
        "IsEnabled" : "false",
        "class" : "UITextField",
        "width" : 238,
        "parent" : {
          "class" : "UIView",
          "height" : 101,
          "Y" : 192,
          "width" : 280,
          "X" : 20
        },
        "name" : "Enter UserName",
        "X" : 40,
        "isRightOf" : "NA",
        "Recording Device" : "NA",
        "Y" : 0
      },
      {
        "data" : "Enter UserName",
        "type" : "string"
      }
    ],

  }
]

我也尝试过GSON库来读取JSON文件。但是失败了。请帮忙

2 个答案:

答案 0 :(得分:1)

您提供的JSON无效(逗号无效)

[
  {
    "arguments" : [
      {
        "IsEnabled" : "false",
        "class" : "UITextField",
        "width" : 238,
        "parent" : {
          "class" : "UIView",
          "height" : 101,
          "Y" : 192,
          "width" : 280,
          "X" : 20
        },
        "name" : "Enter UserName",
        "X" : 40,
        "isRightOf" : "NA",
        "Recording Device" : "NA",
        "Y" : 0
      },
      {
        "data" : "Enter UserName",
        "type" : "string"
      }
    ], <-- this comma makes the json invalid

  }
]

答案 1 :(得分:0)

您的输入json错误,建议丢失逗号。

Json对象很难解析,但如果你曾经得到过如何解析json数据的概念,那就很容易了。

您需要查看您尝试访问的属性是json数组还是对象。如果您是初学者,这是基本规则。

这是代码::

OUTOUT IS ::

arguments>>>>>>>>> [{"parent":{"width":280,"X":20,"Y":192,"class":"UIView","height":101},"Recording Device":"NA","IsEnabled":"false","width":238,"name":"Enter UserName","X":40,"isRightOf":"NA","Y":0,"class":"UITextField"},{"data":"Enter UserName","type":"string"}]
{"parent":{"width":280,"X":20,"Y":192,"class":"UIView","height":101},"Recording Device":"NA","IsEnabled":"false","width":238,"name":"Enter UserName","X":40,"isRightOf":"NA","Y":0,"class":"UITextField"}
{"data":"Enter UserName","type":"string"}

所以,在代码中你可以看到我有时会采用json数组并且有时会对象,你需要区分它们。

import java.io.FileReader;
import java.io.IOException;

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


public class test {

    public static void main(String[] args) throws IOException, InterruptedException {
        JSONParser parser = new JSONParser();
        try {
            Object obj = parser.parse(new FileReader("test.json"));
            JSONArray jsonObject = (JSONArray) obj;
            JSONObject arr = (JSONObject) jsonObject.get(0);
            JSONArray arguments = (JSONArray) arr.get("arguments");
            System.out.println("arguments>>>>>>>>> "+arguments);
            for(int i = 0 ; i< arguments.size() ;i++){
                JSONObject object = (JSONObject) arguments.get(i);
                System.out.println(object);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}