java

时间:2016-10-07 08:48:37

标签: java json

如果我的JSON文件是这样的:

{"result":[{"sentence": "Chinese government cafes people cafe crackdown", "id": 1, "txtfile": "002.txt"}, {"sentence": "kalf alo ldk alf", "id": 2, "txtfile": "003.txt"}]}

如何将.json文件读入java并解析JSON来获取句子,id,txtfile?因为我的json包含JSONARRAY和JSONOBJECT。

private static String jsonFile="D:\\MYJSON.json";

    public static void main(String[] args){

        JSONParser parser = new JSONParser();

        try{

            Object obj=parser.parse(new FileReader(jsonFile));  
            JSONObject jsonObject = (JSONObject) obj;
            String sentence=(String) jsonObject.get("sentence");
            System.out.println(sentence);
} catch (Exception e){
        e.printStackTrace();
    }
    }
}

我的错误为:java.lang.ClassCastException:java.lang.String无法强制转换为org.json.JSONObject     在yyym.ttt.main(ttt.java:46)

这是我的JSON

"{\"result\":[{\"sentence\": \"said Chinese government cafes people cafe crackdown\", \"id\": 1, \"txtfile\": \"002.txt\"}, {\"sentence\": \"kalf alo ldk alf\", \"id\": 2, \"txtfile\": \"003.txt\"}]}"

我检查了我的JSON文件是否有效。 但是,当我把它打印出来。它以“,如何解决问题?”开头。

the output is     "{\"result\":[{\"sentence\": \"said Chinese government cafes people cafe crackdown\", \"id\": 1, \"txtfile\": \"002.txt\"}, {\"sentence\": \"kalf alo ldk alf\", \"id\": 2, \"txtfile\": \"003.txt\"}]}"
org.json.JSONException: A JSONObject text must begin with '{' at 1 [character 2 line 1]
    at org.json.JSONTokener.syntaxError(JSONTokener.java:451)
    at org.json.JSONObject.<init>(JSONObject.java:195)
    at org.json.JSONObject.<init>(JSONObject.java:319)
    at yyym.ttt.main(ttt.java:26)

enter image description here

5 个答案:

答案 0 :(得分:2)

结果是一个数组,首先你必须得到那个数组,遍历那个数组,然后得到所需的json对象。

以下代码中使用的库是 - org.json

代码

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class Example {

    public static void main(String[] args) {

        //String jsonString = "{\"result\":[{\"sentence\": \"Chinese government cafes people cafe crackdown\", \"id\": 1, \"txtfile\": \"002.txt\"}, {\"sentence\": \"kalf alo ldk alf\", \"id\": 2, \"txtfile\": \"003.txt\"}]}";

        String jsonString = readJsonFile("filePath");

        try {
            JSONObject jsonObject = new JSONObject(jsonString);
            JSONArray result = jsonObject.getJSONArray("result");
            for (int i =0; i < result.length(); i++){
                JSONObject j = result.getJSONObject(i);
                String s = j.getString("sentence");
                int id = j.getInt("id");
                String txtFile = j.getString("txtfile");
                System.out.println("Sentence is " + s);
                System.out.println("Id is " + id);
                System.out.println("text file is " + txtFile);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    public static String readJsonFile(String filePath) {
    String jsonData = "";
    BufferedReader br = null;
    try {
        String line;
        br = new BufferedReader(new FileReader(filePath));
        while ((line = br.readLine()) != null) {
            jsonData += line + "\n";
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            if (br != null) {
                br.close();
            }
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
    return jsonData;
}
}

输出

  1. 句子是中国政府咖啡馆人民咖啡馆镇压。
  2. Id为1
  3. 文本文件为002.txt
  4. 句子是kalf alo ldk alf
  5. Id为2
  6. 文本文件为003.txt

答案 1 :(得分:1)

我正在使用这个jars文件:jsonsimple.jar

http://www.java2s.com/Code/Jar/j/Downloadjsonsimplejar.htm

 private static String jsonFile="D:\\MYJSON.json";
 public static void main(String[] args) {

        JSONParser parser = new JSONParser();

        try {

            Object obj = parser.parse(new FileReader(jsonFile));
            JSONObject jsonObject = (JSONObject) obj;
            System.out.println("KK:"+jsonObject.toString());
            JSONArray jarray = (JSONArray) jsonObject.get("result");
            for (int i=0;i<jarray.size();i++) {
                jsonObject = (JSONObject) jarray.get(i);
                String sentence = (String)jsonObject.get("sentence"); 
             System.out.println(sentence);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

输出:

{"result":[{"sentence":"Chinese government cafes people cafe crackdown","txtfile":"002.txt","id":1},{"sentence":"kalf alo ldk alf","txtfile":"003.txt","id":2}]}
Chinese government cafes people cafe crackdown
kalf alo ldk alf

答案 2 :(得分:0)

 String sentence=null;
    JSONArray jsonArray = jsonObject.getJSONArray("result");
    if(jsonArray.length()>0){
     for(int i=0;i<jsonArray.length();i++){
        JSONObject jo=jsonArray.getJSONObject(i);
        sentence=jo.getString("sentence");
       }
   }

答案 3 :(得分:0)

结果是JsonArray,你可以循环它来获取JsonObjects,例如:

Object obj=parser.parse(new FileReader(jsonFile));  
JSONObject jsonObject = (JSONObject) obj;
JSONArray values = item.json.optJSONArray("result");
JSONObject json;
String sentence = "";
//loop to get object
for (int i = 0; i < values.length(); i++){
    json = values.getJSONObject(i);
    //get sentenence
    sentence = json.getString("sentence");
}

答案 4 :(得分:0)

使用instanceof检查该数据是JsonObject还是JsonArray

下面给出的示例代码

public void main() {
    String jsonFile = "D:\\MYJSON.json";
    JSONParser parser = new JSONParser();
    try {
        Object obj = parser.parse(new FileReader(jsonFile));
        if (obj instanceof JSONObject) {
            JSONObject jsonObject = (JSONObject) obj;
            String sentence = jsonObject.optString("sentence");
            System.out.println(sentence);
        } else if (obj instanceof JSONArray) {
            JSONArray jsonArray = (JSONArray) obj;
            for (int i = 0; i < jsonArray.length(); i++) {
                JSONObject jsonObj = jsonArray.getJSONObject(i);
                String sentence = jsonObj.optString("sentence");
                System.out.println(sentence);
            }//end of for loop
        }//end of else if
    } catch (Exception e) {
        e.printStackTrace();
    }
}