编程知识 cdmana.com

Java and JSON

Java And JSON

JSON It's a format for transferring information between different programs . This article describes JSON stay Java Application in .
at present Java The most popular analysis tools are provided by Google Gson And Ali FastJSON .

One 、JSON Format

JSON: JavaScript Object Notation(JS Object shorthand ), Is a lightweight data exchange format .
For example, a Book , Yes id The property value is "1001", Yes name The property value is "book", Yes info The property value is " brief introduction ", use JSON Shown by the following :

{
  "id":"1001",
  "name":"book",
  "info":" brief introduction "
}

in addition ,JSON The format can also contain arrays ( Include in brackets [,,,]), Objects can also be nested within each other .
Like a cabinet , The name is " Bookcase ", There is one "books" Attribute contains three books , One more belong Property means that it belongs to someone , It can be expressed as :

{
  "name":" Bookcase ",
  "books":["book1","book2",{
    "id":"1001",
    "name":"book",
    "info":" brief introduction "
  }],
  "belong":{
    "name":" Zhang San ",
    "age":18,
  }
}

Two 、Java And JSON

1. Gson

Use Gson Class can extract a string containing JSON The information in the string of , You can also save the information of a class to a string of JSON In a string .
The following code uses Book Classes and Cabinet The categories are as follows

class Book {
    private int id;
    private String name;
    private String info;
    public String toString() {
        return "name:" + name + ", info:" + info;
    }
}
class Cabinet {
    private String name;
    private Book[] books;
    private String belong;
    public String toString() {
        return "Cabinet{" +
                "name='" + name + '\'' +
                ", books=" + Arrays.toString(books) +
                ", belong='" + belong + '\'' +
                '}';
    }
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Cabinet cabinet = (Cabinet) o;
        return Objects.equals(name, cabinet.name) && Arrays.equals(books, cabinet.books) && Objects.equals(belong, cabinet.belong);
    }
    public int hashCode() {
        int result = Objects.hash(name, belong);
        result = 31 * result + Arrays.hashCode(books);
        return result;
    }
    public Cabinet() {
    }
    public Cabinet(String name, Book[] books, String belong) {
        this.name = name;
        this.books = books;
        this.belong = belong;
    }
}
  • Save information : toJson(Object src) Method
    • Save a class as json Format
    import com.google.gson.Gson;
    public class Demo1 {
        public static void main(String[] args) {
            //  establish  Gson  object 
            Gson gson = new Gson();
            Book b = new Book(1001, "book", "info");
            //  Put an object  b  Convert to  json  character string 
            String s = gson.toJson(b);
            System.out.println(s);
        }
    }
    
    • Save a collection as json Format
    import com.google.gson.Gson;
    import java.util.ArrayList;
    public class Demo2 {
        public static void main(String[] args) {
            //  establish  Gson  object 
            Gson gson = new Gson();
            ArrayList<Object> list = new ArrayList<>();
            list.add("abc");
            list.add(new Book(1001, "book", "info"));
            //  Put a collection  list  Convert to  json  character string 
            String s = gson.toJson(list);
            System.out.println(s);
        }
    }
    
    • Use a complex object with json Format saved to file
    import com.google.gson.Gson;
    import java.io.*;
    public class Demo3 {
        public static void main(String[] args) throws IOException {
            //  establish  Gson  object 
            Gson gson = new Gson();
            //  Convert a complex object to a string 
            String s = gson.toJson(new Cabinet("Cabinet",
                    new Book[]{new Book(1001, "book1", "info1"),
                            new Book(1002, "book2", "info2"),
                            new Book(1003, "book3", "info3")}, " Zhang San "));
            //  Write the obtained string to a file 
            FileWriter fw = new FileWriter("cabinet.json");
            fw.write(s);
            fw.close(); //  Remember to turn off the stream !
        }
    }
    
  • Extract information : fromJson(String json, Class classOfT) Method
    • Extract a class
    import com.google.gson.Gson;
    public class Demo4 {
      public static void main(String[] args) {
        Gson gson = new Gson();
        // {"name":"book","info":"abc"}
        Book book = gson.fromJson("{\"name\":\"book\",\"info\":\"abc\"}", Book.class);
        System.out.println(book);
      }
    }
    
    • Extract an array
    import com.google.gson.Gson;
    import java.util.List;
    public class Demo5 {
      public static void main(String[] args) {
        // ["abc","bcd","cde"]
        List list = new Gson().fromJson("[\"abc\",\"bcd\",\"cde\"]",List.class);
        for (Object s : list) {
          System.out.println(s);
        }
      }
    }
    
    • Extract a more complex class from the file
    import com.google.gson.Gson;
    import java.io.BufferedReader;
    import java.io.FileReader;
    import java.io.IOException;
    public class Demo6 {
        public static void main(String[] args) throws IOException {
            //  The file used here is saved in the code above  cabinet.json  file 
            //  Read the data in the file 
            BufferedReader br = new BufferedReader(new FileReader("cabinet.json"));
            String s = br.readLine();
            br.close(); //  Don't forget to turn off !
            //  establish  Gson  object 
            Gson gson = new Gson();
            //  If we don't  Cabinet  This class , It can be transformed into  HashMap  object 
            HashMap hashMap = gson.fromJson(s, HashMap.class);
            //  Print all 
            System.out.println(hashMap);
            List<Book> list = (List<Book>) hashMap.get("books");
            //  Print  books
            System.out.println(list.get(1));
        }
    }
    

Be careful :JSON The string should correspond to each property name of the corresponding class , If JSON A property name that does not exist in the corresponding class appears in the string , Then this property will be ignored . Empathy , If JSON There is no property in the corresponding class in the string , Then this property of the corresponding class is set to the default value .

2.FastJSON

Use FastJSON Extract or save json String method :

  • Save information : toJSONString(Object object) Method
    Be careful : Use FastJSON Each property of the saved class must have get Method , Otherwise, you can't save . above Book Class does not provide get Method , Can't save .
    • Save information about a class
    import com.alibaba.fastjson.JSON;
    public class Demo {
        public static void main(String[] args) {
            //  Let's assume that this class provides  get  Method 
            Book b = new Book(1001, "book", "info");
            //  Turn into  JSON  character string 
            String s = JSON.toJSONString(b);
            //  Print it out and check for correctness 
            System.out.println(s);
        }
    }
    
    • Save a collection ( Array ) Information about
    import com.alibaba.fastjson.JSON;
    public class Demo {
        public static void main(String[] args) {
            //  hypothesis  Book  Class available  get  Method 
            Book[] b = new Book[]{new Book(1001, "book", "info"), new Book(1002, "abc", "ofni")};
            String s = JSON.toJSONString(b);
            System.out.println(s);
        }
    }
    
    • Save a more complex class to a file
    import com.alibaba.fastjson.JSON;
    import java.io.FileWriter;
    import java.io.IOException;
    public class Demo {
        public static void main(String[] args) throws IOException {
            Book b1 = new Book(1001, "1", "a");
            Book b2 = new Book(1002, "2", "b");
            Book b3 = new Book(1003, "3", "c");
            Book[] bs = {b1, b2, b3};
            Cabinet c = new Cabinet("cabinet", bs, "abc");
            String json = JSON.toJSONString(c);
            FileWriter fw = new FileWriter("cabinet2.json");
            fw.write(json);
            fw.close();
        }
    }
    
  • pick up information : parseObject(String text, Class clazz) Method
    Be careful : The class that gets the information must provide Nonparametric construction method , Otherwise JSONException abnormal
    • Get information about a class
    import com.alibaba.fastjson.JSON;
    public class Demo {
        public static void main(String[] args){
            // {"id":1001,"name":"b","info":"1"}
            Book b = JSON.parseObject("{\"id\":1001,\"name\":\"b\",\"info\":\"1\"}", Book.class);
            System.out.println(b);
        }
    }
    
    • Get an array information
    import com.alibaba.fastjson.JSON
    import java.io.IOException;
    import java.util.List;
    public class Demo {
        public static void main(String[] args) {
            // ["",{"id":123,"name":"abc"},null]
            List list = (List) JSON.parse("[\"\",{\"id\":123,\"name\":\"abc\"},null]");
            System.out.println(list.get(1));
        }
    }
    
    • Get a more complex object from a file
    import com.alibaba.fastjson.JSON;
    import java.io.BufferedReader;
    import java.io.FileReader;
    import java.io.IOException;
    import java.util.HashMap;
    import java.util.List;
    public class Demo {
        public static void main(String[] args) throws IOException {
            BufferedReader br = new BufferedReader(new FileReader("cabinet2.json"));
            String s = br.readLine();
            HashMap hashMap = JSON.parseObject(s, HashMap.class);
            System.out.println(hashMap);
            List list = (List) hashMap.get("books");
            System.out.println(list.get(1));
            HashMap book2 = JSON.parseObject(list.get(1).toString(), HashMap.class);
            System.out.println(book2.get("name"));
        }
    }
    

版权声明
本文为[——light]所创,转载请带上原文链接,感谢
https://cdmana.com/2021/05/20210524234322560R.html

Tags java json
Scroll to Top