-3

我有以下 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。

如何将其反序列化为对象?

4

5 回答 5

11

您可以使用这样的gson 库将上面的 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);

编辑(基于您编辑的问题):用于将 JSON 转换为您的 POJO 对象

您可以使用 gson将 JSON 字符串转换为您的自定义 POJO,如下所示:

// assuming your POJO is of type MyClass
MyClass instance = gson.fromJson(jsonStr, MyClass.class);
于 2013-04-12T11:04:01.160 回答
3

如果要为上述 json 字符串生成匹配的 java 类,使用 json 生成器将是最好的解决方案,因为数据有很多字段。

您可以查看http://www.jsonschema2pojo.org/

只需粘贴您的 json,选择 JSON 作为源类型,您将拥有一个与Jackson兼容的带注释的 java 类。

于 2013-04-12T11:02:45.087 回答
3

看看这个库教程:jackson

String myJson = new org.codehaus.jackson.map.ObjectMapper.writeValueAsString(myObject);

于 2013-04-12T11:03:45.297 回答
2

有一些 JSON 库可能会对您有所帮助。例如,Gson是一个 Java 库,可用于将 Java 对象转换为其 JSON 表示形式。它还可用于将 JSON 字符串转换为等效的 Java 对象

于 2013-04-12T11:02:04.990 回答
2

您可以使用 gson 或 JsonOrg 等库创建 JSON 对象。您可以通过以下链接了解库和实现

https://sites.google.com/site/gson/gson-user-guide
http://code.google.com/p/google-gson/
http://json.org/java/
于 2013-04-12T11:02:36.173 回答