JSON数据转为bean List Map

在之前的项目中,数据从后台返回到前台,一般是把bean 或List或Map转为转为JSON格式输出,用到JSONObject或者JSONArray。这个容易处理,博客中写的有。
但是,这次在远程接口调用的时候,获取的数据时JSON,但是要取值,却发现不是那么容易。当初想的是转化为bean或List或Map,这样通过get/set,put/get取值赋值。但不容易实现,难道是我引用的json jar包 不对或者是某些方法不熟悉。反正最后,一步步的通过split截取的,之后转化为Map。第二步进行进一步的细化。然后拼装成String.
应该说如果正则表达式写的好的话,也能截取出来,可惜我的正则表达式不行。
所以只好一步步的来操作截取。
第一步程序:
public static Map<String, String> getJSONobject(String str){

String sb = str.substring(1, str.length()-1);
String[] name = sb.split("\\\",\\\"");
String[] nn =null;
Map map = new HashMap();
for(int i= 0;i<name.length; i++)
{
nn = name[i].split("\\\":\\\"");
map.put(nn[0], nn[1]);
}
return map;
}

第二步程序根据需求处理字符串,符合实际要求
public static String chuliString(Map<String,String> map){
String conventionSuggestions =null;
String sportSuggestion = null;
String foodSuggestion = null;
String doctorSuggestion = null;
String advice = null;;

Iterator<Entry<String,String>> iter = map.entrySet().iterator();
while(iter.hasNext()) {
Entry<String, String> entry = iter.next();
if((entry.getKey()).equals("conventionSuggestion")){
String conventionSuggestion = entry.getValue();
conventionSuggestions = conventionSuggestion.split("}")[0];
; System.out.println("conventionSuggestions="+conventionSuggestions.substring(0, conventionSuggestions.length()-1));
}
if((entry.getKey()).equals("suggestion':{'sportSuggestion")){
sportSuggestion = entry.getValue();
System.out.println("sportSuggestion="+sportSuggestion);
}
if((entry.getKey()).equals("foodSuggestion")){
foodSuggestion = entry.getValue();
System.out.println("foodSuggestion="+foodSuggestion);
}
if((entry.getKey()).equals("doctorSuggestion")){
doctorSuggestion = entry.getValue();
System.out.println("doctorSuggestion="+doctorSuggestion);
}
}
advice = conventionSuggestions+","+sportSuggestion+","+foodSuggestion+","+doctorSuggestion;
System.out.println("advice="+advice);
return advice ;
}
第二步程序:需求不一样,逻辑也就不同,但是处理方式是一样的,可以参考一下。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值