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());
      
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值