gson and json

gson强大的地方是可以反解析


//从文件过去json File file = new File(GsonT.class.getResource("json.sjon").getFile()); String s = FileUtils.readFileToString(file); Gson gson = new Gson(); Diaosi diaosi = gson.fromJson(s, Diaosi.class); //gson转换日期格式
File file = new File(GsonT.class.getResource("json.sjon").getFile());
String s = FileUtils.readFileToString(file);
Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd").create();
Diaosi diaosi1 = gson.fromJson(s, Diaosi.class);
System.out.println(diaosi1.getBirthDay().toString());
System.out.println(diaosi1.getMajor());
System.out.println(diaosi1.getMajor().getClass());//java.util.Array
System.out.println(diaosi1.getMajor().getClass());//修改diaosi类的major类型为Set.gson会自动转换成java.util.Set


//最基本的json操作 JSONObject json = new JSONObject(); Object nullObj=null; json.put("name","王小二"); //gonsBuilder格式 GsonBuilder gb=new GsonBuilder(); gb.setPrettyPrinting(); gb.setFieldNamingStrategy(new FieldNamingStrategy() { public String translateName(Field field) { if(field.getName().equals("name")){ return "Name"; } return field.getName(); } }); Gson gson1 = gb.create(); System.out.println(gson1.toJson(diaosi)); //获取数组jsonarray File file = new File(JsonObjectOne.class.getResource("/j.json").getFile()); String content = FileUtils.readFileToString(file); JSONObject jsonObject = new JSONObject(content); if(!jsonObject.isNull("name")){ } if(!jsonObject.isNull("nickname")){ } JSONArray jsonArray = jsonObject.getJSONArray("major"); for(int i=0;i<jsonArray.length();i++){ String m=(String)jsonArray.get(i); }

  

posted @ 2019-01-06 12:18  uuhh  阅读(244)  评论(0编辑  收藏  举报