上面的字符串怎么得到名字name后根据名字得到相对于的价格price?或者说把这些数据分别做成一个单独的字符串就是 分别把每个名字 价格 id 之类的分别放到一个array里?然后再根据name得到相应的价格?
楼主,上面的community改成communityId,手误,测试结果:
{"油烟机":{"aprice":22,"community":0,"id":33,"priStatus":0},"洗衣机":{"aprice":42,"community":0,"id":40,"priStatus":0},"电视机":{"aprice":25,"community":0,"id" :32,"priStatus":0}}
json字符串转json对象 然后取key
可以使用Gson 或者 fastJson 直接将json字符串转成对象数组
一。
.遍历json数组,根据name获取json对象,在有key取出json里面的price
二
遍历json数组,将不同name对应的value放进nameArray中,将不同price对应的value放进priceArray,根据name取得在name数组的下标,用这个小标
去priceArrray获取price
把上面的字符串传给这个方法,由于是map,所以查找很快。楼主给个采纳吧
public static Map<String,Map<String,Double>> parse(String str){
Map<String,Map<String,Double>> map=new HashMap<String,Map<String,Double>>();
String name="";
Pattern p1=Pattern.compile("(?<=\\{)[^\\{&&[^\\}]]+(?=\\})");
Matcher m=p1.matcher(str);
Pattern pname=Pattern.compile("(?<=\')[\u4e00-\u9fa5]+(?=\')");
Pattern pther=Pattern.compile("(?<==)[\\d]+\\.?[\\d]*");
while(m.find()){
Map<String,Double> subMap=new HashMap<String,Double>();
String s1=m.group();
String[] arr=s1.split(",");
for(String s:arr)
System.out.println(s);
Matcher mname=pname.matcher(arr[0]);
if(mname.find())
name=mname.group();
for(int i=1;i<arr.length;i++){
Matcher other=pther.matcher(arr[i]);
if(other.find())
arr[i]=other.group();
}
subMap.put("id", Double.parseDouble(arr[1]));
subMap.put("community", Double.parseDouble(arr[2]));
subMap.put("aprice", Double.parseDouble(arr[3]));
subMap.put("priStatus", Double.parseDouble(arr[4]));
map.put(name, subMap);
}
return map;
}