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

ε祈祈猫儿з 提交于 2019-12-11 07:32:28

问题


How do I parse this particular json string with Gson in Java?

{"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.


回答1:


You have to create java types that it can be mapped to. 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.




回答2:


Now, you can use json-path in java, see document. It's simple and clever. http://code.google.com/p/json-path/



来源:https://stackoverflow.com/questions/5749125/how-do-i-parse-json-string-that-contains-list-with-gson

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!