string 转 java对象、转map的方式

1、使用fastJson 将String转 map:

String out;

        Object succesResponse = JSON.parse(out);    //先转换成Object

        Map map = (Map)succesResponse;         //Object强转换为Map

2、String 转 java 对象

fastjson 应用 string字符串转换成java对象或者对象数组

代码如下

[java] view plain copy
 
  1. import java.util.ArrayList;  
  2. import java.util.Arrays;    
  3. import java.util.List;    
  4.     
  5. import com.alibaba.fastjson.JSON;    
  6. import com.alibaba.fastjson.JSONObject;  
  7. import com.alibaba.fastjson.TypeReference;    
  8.     
  9.     
  10. public class TestFastJson {      
  11.     public static void main(String[] args) {      
  12.         //  转换成对象      
  13.         String jsonstring = "{"a":51,"b":0}";      
  14.         Usa u1 = JSON.parseObject(jsonstring, new TypeReference<Usa>(){});    
  15.         Usa u2 = JSON.parseObject(jsonstring,Usa.class);    
  16.         // 转换成对象数组       
  17.         String jsonstring2 = "[{"a":51,"b":0}]";      
  18.         Usa[] usa2 = JSON.parseObject(jsonstring2, new TypeReference<Usa[]>(){});      
  19.         List list = Arrays.asList(usa2);   
  20.         // 转换成ArrayList  
  21.         ArrayList<Usa> list2 = JSON.parseObject(jsonstring2, new TypeReference<ArrayList<Usa>>(){});   
  22.           
  23.         // 转换成ArrayList(默认)    list3  与 list4  效果相同  
  24.         ArrayList<JSONObject> list3 = JSON.parseObject(jsonstring2, new ArrayList<Usa>().getClass());   
  25.         ArrayList<JSONObject> list4 = JSON.parseObject(jsonstring2, ArrayList.class);   
  26.         for (int i = 0; i < list4.size(); i++) { //  推荐用这个  
  27.             JSONObject io = list4.get(i);  
  28.             System.out.println(io.get("a") + "======adn====="+io.get("b"));  
  29.         }  
  30.     }      
  31. }      
  32. class Usa {  
  33.     private int count = 1888;  
  34.     private String base = "project";  
  35.     private Long a;      
  36.     public Long getA() {      
  37.         return a;      
  38.     }      
  39.     public void setA(Long a) {      
  40.         this.a = a;      
  41.     }      
  42.     private String b;      
  43.     public String getB() {      
  44.         return b;      
  45.     }      
  46.     public void setB(String b) {      
  47.         this.b = b;      
  48.     }      
  49. }      
  50.    

json字符串 直接转换成List

[java] view plain copy
 
  1. ArrayList<Usa> usa2 = JSON.parseObject(jsonstring2, new TypeReference<ArrayList<Usa>>(){});   

 或者转换成对象数组

   Usa[] usa2 = JSON.parseObject(jsonstring2, new TypeReference<Usa[]>(){});  

  对象数组转List  

   List list = Arrays.asList(usa2);    

我们使用new TypeReference的时候会生成多个class文件 里面有多少个new TypeReference 就会新增了class

即使我们在for循环里(0-N)写new TypeReference 这段代码也是多生成一个class文件,fastjson是看我们写了多少new TypeReference,而不是调用了多少次new TypeReference。推荐用ArrayList.class 

原文地址:https://www.cnblogs.com/remember-forget/p/9045180.html