Javaリスト<マップ<文字列、オブジェクト>>とjson相互変換、リスト<エンティティ>とjson相互変換

序文:

JSONArray:List <-Object>
と同等JSONObject:Map <String、Object>と同等

1、List <Map <String、Object >>変換json(String)


 String sql=" select * from table";
 List<Map<String, Object>> list= jdbcTemplate.queryForList(sql);
 String str = JSON.toJSONString(list); //此行转换

json形式のデータ:

	[{
		"formid": "1",
		"fieldname": "ID",
		"xh": 1,
		"bz": "1",
		"fieldzhname": "ID",
		"id": "9b3ef259-4ea5-4137-ad8d-2c4f3534ae12",
		"pkey": 1
	}, {
		"formid": "1",
		"fieldname": "VERSION",
		"xh": 2,
		"bz": "2",
		"fieldzhname": "数据版本",
		"id": "858b7e4d-ec6f-480d-b5e7-dbad91b040eb",
		"pkey": 0
	}]

2、json変換リスト<マップ<文字列、オブジェクト>>

	String json="[{XXXXXX}]";
	List< Map<String,Object>> listw = toListMap(json); //此行转换
	
	public static List<Map<String, Object>> toListMap(String json){
    
    
	       List<Object> list =JSON.parseArray(json);
	       List< Map<String,Object>> listw = new ArrayList<Map<String,Object>>();
	       for (Object object : list){
    
    
	           Map<String,Object> ageMap = new HashMap<String,Object>();
	           Map <String,Object> ret = (Map<String, Object>) object;//取出list里面的值转为map
	           listw.add(ret);
	       }
	       return listw;     
	 } 
    

3. JSON.parse()は、json文字列をオブジェクトに変更します

タイプ:リスト-文字列-オブジェクト

                                                    
List<Map<String,Object>> list=jdbcTemplate.queryForList(sql);
hashmap.put("fielddata",JSON.parse(JSON.toJSONString(list)));

4.jsonをList <entity>に変換します

インポートされたパッケージは次のとおりです。


 import cn.hutool.json.JSONUtil;
 import com.alibaba.fastjson.JSON;
 import cn.hutool.json.JSONArray;
 import com.alibaba.fastjson.JSONObject
 

  List<Entity> list =new LinkedList<>();
  String json="[{XXXXXX}]";
  JSONArray picArray = new JSONArray(json);
  list = JSONUtil.toList(picArray , Entity.class); 
   

5. List <Entity>をjson(文字列)に変換します


 import cn.hutool.json.JSONUtil;
 import com.alibaba.fastjson.JSON;
 import cn.hutool.json.JSONArray;
 import com.alibaba.fastjson.JSONObject
 

  // List<Entity> list 
  String json=JSON.toJSON(list).toString();
 

参考記事:

1. List <Map <String、Object >>とjsonの間で変換します

おすすめ

転載: blog.csdn.net/qq_36636312/article/details/111224047