我有以下JSON字符串。
{"portfolio":"HEXGENFUND","transSrlNo":"1","transCode":"BUY","investReason":"009","inflowOutflow":"I","transDate":"2012-09-01","tradeDate":"2012-09-01","tradeDateUpto":"2012-09-01","tradeTime":"15:46:36","investCategory":"FVTPL","custodian":"DEUTSCHE","holdType":"HOLD","securityType":"INV","security":"9.45SBAI160326","assetClass":"NCD","issuer":"SBAI","marketType":"LIM","tradePriceType":"R","requisitionType":"MS","priceFrom":"343490934332","priceTo":"343490934332","marketPrice":"343490934332","averagePrice":"343490934332","price":"343490934332","quantity":"234","grossAmtTcy":"80376878633688","exchRate":"1","grossAmtPcy":80376878633688,"grossIntTcy":"992.42","grossIntPcy":992.42,"netAmountTcy":80376878634680.42,"netAmountPcy":80376878634680.42,"acquCostTcy":80376878633688,"acquCostPcy":80376878633688,"yieldType":"N","purchaseYield":"0","marketYield":"0","ytm":"-80.07453968","mduration":"0","currPerNav":"0","desiredPerNav":"0","currHolding":"0","noofDays":"0","realGlPcy":0,"realGlTcy":"0","nowLater":"N","isAllocable":"false","acquCostReval":0,"acquCostHisTcy":80376878633688,"acquCostHisPcy":0,"exIntTcy":0,"exIntPcy":0,"accrIntReval":0,"accrIntTcy":0,"accrIntPcy":0,"grossAodTcy":0,"grossAodPcy":0,"grossAodReval":0,"bankAccAmtAcy":80376878634680.42,"bankAccAmtPcy":80376878634680.42,"taxAmountTcy":0,"unrelAmortTcy":0,"unrelAmortPcy":0,"unrelGlTcy":0,"unrelGlPcy":0,"realGlHisTcy":0,"realGlHisPcy":0,"tradeFeesTcy":0,"tradeFeesPcy":0}
我有上面的POJO。
如何将其反序列化为对象?
答案 0 :(得分:11)
您可以像这样使用gson library将上面的JSON字符串转换为HashMap:
Gson gson = new Gson(); // get a new Gson instance
// define a Type for Map<String, String>
Type type = new TypeToken<Map<String, String>>(){}.getType();
// convert JSON string to a Map<String, String> instance
Map<String, String> map = gson.fromJson(jsonStr, type);
您可以使用gson 将JSON字符串转换为您的自定义POJO:
// assuming your POJO is of type MyClass
MyClass instance = gson.fromJson(jsonStr, MyClass.class);
答案 1 :(得分:3)
如果你想为上面的json字符串生成匹配的java类,那么使用json生成器将是最好的解决方案,因为数据有很多字段。
您可以查看http://www.jsonschema2pojo.org/
只需粘贴您的json,选择JSON作为源类型,您将拥有一个Jackson兼容的带注释的Java类。
答案 2 :(得分:3)
看看这个图书馆教程:jackson
String myJson = new org.codehaus.jackson.map.ObjectMapper.writeValueAsString(myObject);
答案 3 :(得分:2)
有一些JSON库可以帮助您。 例如,Gson是一个Java库,可用于将Java对象转换为其JSON表示。它还可用于将JSON字符串转换为等效的Java对象
答案 4 :(得分:2)
您可以使用gson或JsonOrg等库创建JSON对象。您可以通过以下链接获取库和库实现
https://sites.google.com/site/gson/gson-user-guide
http://code.google.com/p/google-gson/
http://json.org/java/