Gson converts between Java POJO and Json data strings

Gson converts between Java POJO and Json data strings

E.g:

        POJO pojo = new POJO ();
        pojo.name = "zhangphil";
        pojo.id = 1;
        pojo.strings = new ArrayList<>();
        pojo.setBlog("zhangphil @ csdn");

        for (int i = 0; i < 10; i++) {
            pojo.strings.add(String.valueOf(i));
        }

        Gson gson = new Gson ();
        String s = gson.toJson (pojo);
        Log.d("Convert POJO to Json string", s);

        POJO pojo2 = gson.fromJson (s, POJO.class);
        Log.d("Json string converted to POJO", pojo2.name + " , " + pojo2.id + " , " + pojo2.getBlog() + " , " + pojo2.strings.size());

POJO :

   private class POJO {
        public String name;
        public int id;
        public ArrayList<String> strings;

        //Private variables are also possible, but you need to write get and set methods
        private String blog;

        public void setBlog(String blog) {
            this.blog = blog;
        }

        public String getBlog() {
            return blog;
        }
    }



    private class POJO {
        public String name;
        public int id;
        public ArrayList<String> strings;

        //Private variables are also possible, but you need to write get and set methods
        private String blog;

        public void setBlog(String blog) {
            this.blog = blog;
        }

        public String getBlog() {
            return blog;
        }
    }


Using the convenience of mutual conversion between POJO and Json strings, data can be passed between Android Activity and Fragment when jumping. Pass it to Bundle or Intent string, and then use Gson to restore the POJO.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325525114&siteId=291194637