[英]Parsing the JSON result from a Cypher query with Neo4j REST API in Java using JsonReader
我目前編寫了一個程序,該程序使用REST API檢索對Neo4j數據庫進行的Cypher查詢的JSON結果。 該項目是用Android Studio編寫的,其代碼如下:
public class MainActivity extends AppCompatActivity {
private TextView userText;
private Button clicker;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
userText = (TextView) findViewById(R.id.txtUsername);
clicker = (Button) findViewById(R.id.btnClick);
clicker.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
//The REST API needs it's own thread for Neo4j connection. Read up on this documentation.
AsyncTask.execute(new Runnable() {
@Override
public void run() {
try {
//The URL will change based on what is needed for the documentations.
//Provides the address for the HTTP communication.
String neo4jURL = "http://ec2-35-176-79-15.eu-west-2.compute.amazonaws.com:7474/db/data/cypher";
//Helps to create the JSON object used by the query.
//QueryData neo4jqueryData = new QueryData();
//Creates the client used for the connection.
HttpClient neo4jClient = new DefaultHttpClient();
//Assigns the address to either the HttpGet or HttpPost request.
HttpPost neo4jRequest = new HttpPost(neo4jURL);
//Creates the JSON Attributes that will be used as part of the query.
String query = "MATCH (n:Student) WHERE n.Username=\'cs16thm\' RETURN n.StudentID";
JSONObject neo4jJSON = new JSONObject();
neo4jJSON.put("query",query);
//neo4jJSON.put("params","");
String check = neo4jJSON.toString();
Log.d("JSON",check);
StringEntity queryString = new StringEntity(check,"UTF-8");
//Ensures that the application type is JSON.
queryString.setContentType("application/json");
//Adds the Attribute data to the JSON query.
neo4jRequest.setEntity(queryString);
//Adds the Headers to the query.
//bmVvNGo6Z3JvdXAzNw== is the Base64 encoding of the username and password.
neo4jRequest.setHeader("Authorization","Basic bmVvNGo6Z3JvdXAzNw==");
//Shows the data types that would be accepted by the query result.
neo4jRequest.setHeader("Accept", "application/json; charset=UTF-8");
//Used to show the data type being sent to the server.
neo4jRequest.setHeader("Content-Type", "application/json");
//Performs the neo4j query.
HttpResponse queryResult = neo4jClient.execute(neo4jRequest);
//Checks the status code of the request.
int statusCode = queryResult.getStatusLine().getStatusCode();
if (statusCode == 200){
Log.d("CONNECT","Query Made " + Integer.toString(statusCode));
//Gets the results stream from the connection. Results is returned as a JSON which needs to be parsed.
InputStreamReader resultsReader = new InputStreamReader(queryResult.getEntity().getContent());
JsonReader JsonReader = new JsonReader(resultsReader);
//Begins processing of the JSON results.
JsonReader.beginObject();
//Checks all of the parameter keys returned by the document.
Log.d("PARSE","Begin JSON Parse");
while(JsonReader.hasNext()){
//Gathers the name of the current key.
String resultKey = JsonReader.nextName();
Log.d("RESULT","Entered Loop " + resultKey);
//Checks if it's the data we're looking for, and if it contains a value.
if(resultKey.equals("data") && JsonReader.peek() != JsonToken.NULL){
Log.d("RESULT","Entered IF Block");
//Begin array needs to go here.
JsonReader.beginArray();
//Gathers the String value that we require.
String result = JsonReader.nextString();
//Shows the result in the application.
Log.d("RESULT","Result=" + result);
//Prevents further loop execution now that our data is retrieved.
JsonReader.endArray();
break;
} else {
//Skips to the next value if the current one contains nothing of interest.
JsonReader.skipValue();
}
}
Log.d("PARSE","End JSON Parse");
JsonReader.endObject();
//JsonReader.endObject();
//Closes the JSON reader after task to prevent resource hogging.
JsonReader.close();
} else {
Log.d("ERROR", "Request not made " + Integer.toString(statusCode));
}
} catch (MalformedURLException e) {
e.printStackTrace();
Log.d("ERROR", "Bad URL");
} catch (IOException ioe) {
ioe.printStackTrace();
Log.d("ERROR", "Cannot Connect");
} catch (Exception par){
par.printStackTrace();
Log.d("ERROR", "Parse Fail");
}
}
});
}
});
}
}
查詢成功,生成HTTP 200代碼,並且代碼正確運行,直到錯誤消息“ Expected a string but was BEGIN_ARRAY
String result = JsonReader.nextString();
行中引發了Expected a string but was BEGIN_ARRAY
和IllegalStateException
String result = JsonReader.nextString();
。 為了嘗試解決此錯誤,我在JsonReader.beginArray()
添加了JsonReader.beginArray()
和JsonReader.endArray()
行到代碼中。 但是,對於同一行代碼仍會產生相同的錯誤消息。 基於Neo4j文檔, 網址為:( https://neo4j.com/docs/rest-docs/current/ ,第3.6節),我要解析的JSON結果應采用與本示例類似的格式:
{
"columns" : ["n.StudentID"],
"data" : [ ["1607174"] ]
}
最后,當前代碼使用Apache Http Client和Google Simple JSON庫,以防影響任何東西。 對於此問題的任何見解或解決方案都將非常有用,如果您還有其他問題,請隨時提出。 同樣,任何其他允許我正確解析此JSON結果的建議也將受到歡迎。
數據具有嵌套數組: [[]]
"data" : [ ["1607174"] ]
因此,您需要開始內部數組。
JsonReader.beginArray(); // outer
JsonReader.beginArray(); // inner
String result = JsonReader.nextString();
PS可能會遍歷內部數組(如果可能具有多個值)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.