且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2023-01-17 16:48:03

您必须创建可映射到的Java类型。所以,你会有这样的事情。

  public class结果{
private List< Order>命令;
私人号码a;
私人号码b;

//订单,a和b
}

的getter和setter公共类Order {
private Number oid;
私人号码状态;
// getter和setter for oid和status
}

然后你可以只需做一些类似的解析即可。

 结果结果= gson.fromJson(yourSring,Result.class); 

告诫,这是未编译的,未经测试的代码,但应该让您关闭。


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.

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.