Json与Gson

一、json简介:

数据结构:
	Object、Array
基本类型:
	string、number、true、false、null、

二、json数据解析

1、创建maven项目、引入依赖:

<dependency>
 <groupId>org.json</groupId>
 <artifactId>json</artifactId>
 <version>20160810</version>
</dependency>
<dependency>
 <groupId>commons-io</groupId>
 <artifactId>commons-io</artifactId>
 <version>2.4</version>
</dependency>

2、json数据格式、包括基本数据类型:

{
  "name":"link",
  "age":23,
  "birthday":"1995-8-21",
  "school":"xian",
  "major":["计算机","化工"],
  "has_girlfriend":false,
  "car":null
 }

3、转换为json格式的几种方法:

  • 直接存储数据到JSONObject对象:

     private static void JSONObject() throws JSONException{
       JSONObject w=new JSONObject();
       Object nullobj=null;
       w.put("name", "link");
       w.put("age", 23);
       w.put("birthday", "1995-8-21");
       w.put("school", "xian");
       w.put("major", new String[]{"计算机","化工"});
       w.put("has_girlfriend", false);
       w.put("car", nullobj);
       System.out.println(w.toString());
      }
    
  • 将Map型数据通过JSONObject转换:

    private static void createJsonByMap(){
     Map<String,Object> w=new HashMap<String,Object>();
      w.put("name", "link");
    w.put("age", 23);
    w.put("birthday", "1995-8-21");
      w.put("school", "xian");
     w.put("major", new String[]{"计算机","化工"});
     w.put("has_girlfriend", false);
     w.put("car", null);  
     System.out.println(new JSONObject(w));
     }	 
    
  • 将Bean类型的通过JSONObject转换:

      创建Bean:
      public class ObjectBean {
      	 private String name;
      	 private String school;
      	 private boolean has_girlfriend;
      	 private int age;
      	 private Object car;
      	private String[] major;
      	private String birthday;
      }
      private static void createJsonByBean(){
      	 ObjectBean w=new ObjectBean();
      	 w.setAge(23);
      	 w.setBirthday("1995-8-21");
      	 w.setCar(null);
      	 w.setHas_girlfriend(false);
      	 w.setMajor(new String[]{"计算机","化工"});
      	 w.setName("link");
      	 w.setSchool("xian");
      	 System.out.println(new JSONObject(w));
       }
    
  • 从文件中读取数据通过JSONObject转换:

     文件w.json:
     {
      "name":"link",
       "age":23,
      "birthday":"1995-8-21",
       "school":"xian",
       "major":["计算机","化工"],
       "has_girlfriend":false,
       "car":null
      }
      private static void createJsonByReadfile() throws IOException{
       File file=
       new File(JsonObjectSimple.class.getResource("/w.json").getFile());
       String content=FileUtils.readFileToString(file);  
       JSONObject jsonObject=new JSONObject(content); 
     	 if(!jsonObject.isNull("name")){
     	     System.out.println("name:"+jsonObject.getString("name"));
        }
      JSONArray majar=jsonObject.getJSONArray("major");
     	System.out.println(majar);
      }
    

三、gson数据解析:

1、引入依赖:

 <dependency>
 <groupId>com.google.code.gson</groupId>
 <artifactId>gson</artifactId>
 <version>2.8.1</version>
</dependency>

2、gson转换:

  • 将Bean类型的通过Gson转换:

      public void gsonObjectByBean(){
        ObjectBean w=new ObjectBean();
        w.setAge(23);
        w.setBirthday("1995-8-21");
        w.setCar(null);
        w.setHas_girlfriend(false);
        w.setMajor(new String[]{"计算机","化工"});
        w.setName("link");
        w.setSchool("xian");
        w.setIgnore("minmin"); 
        /**
         *  //重命名方式1:
         * @SerializedName("NAME")
         * private String name;
         * 
         *  方式2如下:  
         */  
        GsonBuilder gsonBuilder=new GsonBuilder();
        gsonBuilder.setPrettyPrinting();
        gsonBuilder.setFieldNamingStrategy(new FieldNamingStrategy() {
         @Override
         public String translateName(Field f) {
          if(f.getName().equals("name")){
           return "NAME";
          }
          return f.getName();
         }
        });
        Gson gson1=gsonBuilder.create();
        System.out.println(gson1.toJson(w));
        //通过Gson直接转换
        Gson gson=new Gson();
        System.out.println(gson.toJson(w));
       }
    
  • 读取json文件的通过Gson转换为Bean:

      public void gsonToBeanByReadJson() throws IOException{
        File file=
        new File(GsonCreateSimple.class.getResource("/w.json").getFile());
        String content=FileUtils.readFileToString(file); 
        Gson gson=new Gson();
        //json文件转为bean
        ObjectBean w=gson.fromJson(content, ObjectBean.class);
        //重写toString()
        System.out.println(w);
       }
    
    • 读取json文件的通过Gson转换为Bean(带有Date类型的Bean):
      修改Bean:private Date birthday;

        public void gsonReadDate() throws IOException{
          File file=
          new File(GsonCreateSimple.class.getResource("/w.json").getFile());
          String content=FileUtils.readFileToString(file); 
          Gson gson=
          new GsonBuilder().setDateFormat("yyyy-MM-dd").create();
          ObjectBean1 w=gson.fromJson(content, ObjectBean1.class);
          System.out.println(w.getBirthday().toLocaleString());
          
         }
      
    • 自动解析带有集合类型的Bean:
      private List major;
      private Set major;

        File file=
        new File(GsonCreateSimple.class.getResource("/w.json").getFile());
         String content=FileUtils.readFileToString(file); 
        ObjectBean1 w=gson.fromJson(content, ObjectBean1.class);
         //集合类型List、Set
        System.out.println(w.getMajor());
      
发布了116 篇原创文章 · 获赞 19 · 访问量 3万+
展开阅读全文

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 编程工作室 设计师: CSDN官方博客

分享到微信朋友圈

×

扫一扫,手机浏览