简体   繁体   English

如何使用gson解析包含列表的json字符串?

[英]How do I parse json string that contains list with gson?

How do I parse this particular json string with Gson in Java? 如何在Java中使用Gson解析此特定的json字符串?

{"orders":[{"oid":"347","status":"1"},{"oid":"348","status":"1"}],"a":14.15,"b":0}

What is problematic is the orders list. 有问题的是订单列表。

I suppose one has to use a "type token" parameter to Gson.parse(json,type-toke), but it is not clear to me how this can be done. 我想必须对Gson.parse(json,type-toke)使用“类型令牌”参数,但是我不清楚如何做到这一点。

You have to create java types that it can be mapped to. 您必须创建可以映射到的Java类型。 So, you would have something like this. 因此,您将遇到类似这样的情况。

public class Result {
    private List<Order> orders;
    private Number a;
    private Number b;

    // getter and setter for orders, a, and b
}

public class Order {
    private Number oid;
    private Number status;
    // getter and setter for oid and status
}

Then you can just do the parsing with something like 然后,您可以使用类似

Result result = gson.fromJson( yourSring, Result.class );

caveat, this is uncompiled, untested code, but should get you close. 请注意,这是未经编译,未经测试的代码,但应该可以使您接近。

Now, you can use json-path in java, see document. 现在,您可以在Java中使用json-path,请参阅文档。 It's simple and clever. 简单而聪明。 http://code.google.com/p/json-path/ http://code.google.com/p/json-path/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM