用Java解析json(netbean)
我知道这个问题已经被问过很多次了,但是当我在java中解析json时,我找不到一个好的解决方案。 例如,服务器返回一个字符串 {“键”:“9c4c”} 虽然这可能不是标准的Json,但如何解析这种字符串呢。用Java解析json(netbean),java,json,parsing,Java,Json,Parsing,我知道这个问题已经被问过很多次了,但是当我在java中解析json时,我找不到一个好的解决方案。 例如,服务器返回一个字符串 {“键”:“9c4c”} 虽然这可能不是标准的Json,但如何解析这种字符串呢。 有人能帮忙吗?谢谢这是一种方法,代码注释如下: public class JSONParser { String url; String requestMethod; public JSONParser(String url, String requestMethod
有人能帮忙吗?谢谢这是一种方法,代码注释如下:
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);
}
}
}
你试过什么?我会在一秒钟内发布一些代码,你知道它已经被问过很多次了,所以你大概已经找到了解决方案。为什么您发现的解决方案不够好?你发布的那一点点JSON没有什么不标准的地方。我读过其他帖子,但是这些帖子中的JSON是不同的。我不熟悉json,我的json格式是{“key”:“abc123”},例如,这种格式。我也不知道该进口哪个罐子。非常感谢你的友好回答和帮助,桑德。但是当我遵循您的代码时,我遇到了一个问题:org.json.JSONException:JSONObject[“”]未找到。请问您将如何打印键值以及使用哪个.jar?