如何使用curl在java和解析json响应 [英] How to use curl in java and parse json response
问题描述
我有一个curl命令,提供JSON响应。我想使用这个curl命令在java&在java中解析JSON响应。是否可以这样做?
I have a curl command that gives a JSON response. I want to use this curl command in java & parse the JSON response in java. Is it possible to do so??
编辑:
当我执行以下操作时:
public static void main(String [] args)throws Throwable {
When I do the following: public static void main(String[] args) throws Throwable {
try {
InputStream stream = Runtime.getRuntime().exec("curl --globoff --insecure --silent -u username:password -X GET -H 'Content-Type: application/json' \"http://ficcjira.xyz.com/rest/api/2/search?jql=project=ABC&fields=Timetracking\"").getInputStream();
BufferedReader input = new BufferedReader(new InputStreamReader(stream), 1);
input.readLine();
input.read();
input.read();
DataReader reader = new JsonReader(input)
.addField("TimeSpent", "//array/object/timespent")
.addRecordBreak("//array/object");
/*reader = new TransformingReader(reader)
.add(new BasicFieldTransformer("TimeSpent").stringToDouble());*/
DataWriter writer = new StreamWriter(System.out);
JobTemplate.DEFAULT.transfer(reader, writer);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
我得到以下错误:无法运行程序curl:CreateProcess error = 2,系统找不到指定的文件
推荐答案
这是一个可怕的方式访问Jira Rest api。因为它是一个REST API,你可以在许多方面调用它。其中有些是:
This is a horrible way to access the Jira Rest api. Since it is a REST API, you can call it in many ways. Some of them are:
- 保留Java的Java客户端。 https://marketplace.atlassian.com /plugins/com.atlassian.jira.jira-rest-java-client/server/overview
- Rest Java Client for Java. https://marketplace.atlassian.com/plugins/com.atlassian.jira.jira-rest-java-client/server/overview
我有一些示例代码: https://github.com/somaiah/jrjc
-
Jersey:使用Jersey调用REST API并读取响应。
Jersey: Use Jersey to call the REST APIs and read the responses.
如果您使用Spring,可以使用RestTemplate。我在这里有一个小样本: https://github.com/somaiah/restTemplate
If you are using Spring, you can use the RestTemplate. I have a small sample here: https://github.com/somaiah/restTemplate
当然还有一大堆选择 - Restlet,Apache commons等等。
Of course there is a whole slew of options for you- Restlet, Apache commons and so on.
只有在从bash脚本调用此选项时,才应使用curl选项。在这种情况下,您可以使用jq(我喜欢的)解析响应 https://stedolan.github.io/jq /
You should use the curl option only if you are calling this from a bash script. In that case you can parse the response with jq (which I love) https://stedolan.github.io/jq/
这篇关于如何使用curl在java和解析json响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!