使用GSON将动态字段反序列化为POJO

时间:2015-07-30 13:29:37

标签: java json gson

我已经尝试了很多方法,但没有成功使用Gson库将这个Json解析为Java对象:

 "return":{  
      "48388":{  
         "status":"canceled",
         "operations":{  

         },
         "created":"138232386",
         "price":"12.50000",
         "volume":"50.00000000",
         "pair":"btc_brl",
         "type":"buy"
      },
      "51714":{  
         "status":"canceled",
         "operations":{  

         },
         "created":"1365465421706",
         "price":"1500.00000",
         "volume":"0.10000000",
         "pair":"btc_brl",
         "type":"buy"
      }, 
      "48754":{  
         "status":"canceled",
         "operations":{  

         },
         "created":"1383237058",
         "price":"600.00000",
         "volume":"0.50000000",
         "pair":"btc_brl",
         "type":"buy"
      }
      "success":1
}

有很多关于此的主题,但它们都没有涵盖这种类型的json映射。 我确信有一种简单的方法可以做到这一点,任何想法?谢谢!

编辑: 我试过这个:

public class Test {
    @SerializedName("return")
    public Return1 _return;
}

public class Return {
    public List<Map<String, Order>> order;
}

编辑:

public class Order {
    @SerializedName("id")
    private int idOrder;
    private String status;
    private String created;
    private String price;
    private String volume;
    private String pair;
    private String type;
    private List<Operations> operations;
    // All the gets and sets here..
}

Gson没有初始化我的订单对象。订单对象始终为null。我无法找到实现此映射的正确方法。

1 个答案:

答案 0 :(得分:0)

经过长时间的战斗,我能够使用这个解决方案解决:

public void deserialize() {

Gson gson = new Gson();

// For isr read InputStreamReader
Map<String, Object> map =  gson.fromJson(isr, Map.class);

System.out.println(map.get("success"));
Map<String, Object> map2 = (Map<String, Object>) map.get("return");

// Show the contents of return
System.out.println(map2); 

}

之后我使用Entry对象迭代并设置Order的值。

谢谢!