在Java中解析json(netbean)

时间:2017-06-30 09:44:22

标签: java json parsing

我知道这个问题已被问过很多次了,但是当我在java中解析json时,我找不到一个好的解决方案。 例如,服务器返回一个字符串 { “关键”: “9c4c”} 我怎么能解析这种String,虽然这可能不是标准的Json。 有人可以帮忙吗?感谢

1 个答案:

答案 0 :(得分:0)

这是一种方法,代码被评论说明:

public class JSONParser {
    String url;
    String requestMethod;
    public JSONParser(String url, String requestMethod){
        this.url = url;
        this.requestMethod = requestMethod;
    }
    private String read(BufferedReader bufferedReader) throws IOException {
        //Creates new StringBuilder to avoid escaping chars

        StringBuilder stringBuilder = new StringBuilder();
        //Creates new variable

        String currentLine;
        //Gets the currentLine

        while((currentLine = bufferedReader.readLine()) !=null ){

            //Adds the currentLine to the stringBuild if the currentLine is not null

            stringBuilder.append(currentLine);
        }
        //Returns the StringBuilder is String format

        return stringBuilder.toString();
    }

    public JSONObject sendRequest() throws IOException, JSONException {
        //Get the URL from the constructor

        URL url = new URL(this.url);
        //Opens the connection

        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        //Sets the requestMethod

        connection.setRequestMethod(this.requestMethod);
        //Sets the requestProperties

        connection.setRequestProperty("Content-type", "application/JSON");
        //Tries to read the through the BufferedReader

        try {
            //Creates new BufferedReader & InputStreamReader which get the input of the connection

            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            //Stores the output of the connection in a string

            String jsonText = read(bufferedReader);
            //Creates a new JSON object from the above String

            JSONObject json = new JSONObject(jsonText);
            //Returns the JSON Object

            return json;
        } finally {
            //Disconnects from the URL
            connection.disconnect();
        }
    }

    public void storeJSONData(){
        try{
            //Sends request
            JSONObject json = sendRequest();
            //Gets the JSON array, after that the first JSON object
            json.getJSONArray("").getJSONObject(0).getString("Key");
        }
        catch (IOException e){
            System.out.print(e);
        }
        catch (JSONException e){
            System.out.print(e);
        }


    }
}