如何在Java中使用XStream处理JSON?

时间:2012-04-08 07:14:43

标签: java xstream google-custom-search

我创建了一个Google自定义搜索引擎,并使用HTTP GET启动了查询。现在Google将结果作为JSON格式返回。我只是想知道如何将这个JSON输出格式化为人类可读的方式。

例如:

Title: The matrix
htmlTitle: "The matrix.."

我见过很多论坛都推荐使用XStream。但不确定我怎样才能让它发挥作用。

有人可以帮我解决这个问题吗。

仅供参考,我在这里提供HTTP GET代码:

public static void main(String[] args) throws IOException {

    HttpGet httpget = new HttpGet("https://www.googleapis.com/customsearch/v1?key=AIzaSyBp_5Upf6h0QSXR8UveLs4_c6lAmGW_7B8&cx=014783642332862910131:opc1zgsvfhi&q=matrix&alt=json");
    System.out.println(httpget.getURI());
    ResponseHandler<String> responseHandler = new BasicResponseHandler();
    HttpClient httpClient = new DefaultHttpClient();
    String responseBody = httpClient.execute(httpget, responseHandler);
    System.out.println(responseBody);

1 个答案:

答案 0 :(得分:2)

首先你需要创建一个映射Goolge响应的Class,然后使用这样的代码(来自XStream tutorial):

String json = "{\"product\":{\"name\":\"Banana\",\"id\":\"123\""
        + ",\"price\":\"23.0\"}}";

XStream xstream = new XStream(new JettisonMappedXmlDriver());
xstream.alias("product", Product.class);
Product product = (Product)xstream.fromXML(json);
System.out.println(product.getName());