json数据转化成实体 存到数据库.

转载地址:http://blog.csdn.net/baicp3/article/details/46711067

1.一般我们会调用别人给的webservice获取一个字符串数据。假设为String data=“xxxxxxxxxx”;  这个data其实就是例子EnterpriseInfoEntity 的多条记录

2.  把data转换为JSONArray 

    JSONArray arr =new JSONArray();

   arr = JSONArray.fromObject(data);


3.  我们是调用JSONObject 的toBean方法,讲这条数据对应到我们写的entity 然后在调用保存方法,进行保存

   for(Object obj : arr){

                JSONObject jsonObject =JSONObject.fromObject(obj);
            EnterpriseInfoEntity entInfo = (EnterpriseInfoEntity)JSONObject.toBean(jsonObject, EnterpriseInfoEntity.class);

}





import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
public class Contant {
 public static List> parseJSON2List(String jsonStr) {
  JSONArray jsonarray = JSONArray.fromObject(jsonStr);
  List> list = new ArrayList<>();
  Iterator it = jsonarray.iterator();
  while (it.hasNext()) {
   JSONObject json2 = it.next();
   list.add(parseJSON2Map(json2.toString()));
  }
  return list;
 }
 public static Map parseJSON2Map(String jsonStr) {
  Map map = new HashMap<>();
  try {
   map = mapper.readValue(jsonStr,
     new TypeReference>() {
     });
  } catch (IOException e) {
  }
  return map;
 }
 private static final ObjectMapper mapper = new ObjectMapper();
 public static void main(String[] args) {
  String jsonStr = "";
  // String
  // jsonStr=[{"id":0,"tid":"1","achieve":"1","num":"2","dingding":"3","description":"qwe","dateInfo":"2018-1-25 10:30:8"},{"id":0,"tid":"2","achieve":"4","num":"5","dingding":"6","description":"asd","dateInfo":"2018-1-25 10:30:8"}];
  Contant.parseJSON2List(jsonStr);
 }

你可能感兴趣的:(json数据转化成实体 存到数据库.)