好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

给JavaBean赋默认值并且转Json字符串的实例

JavaBean赋默认值并转Json字符串

今日在工作中整理dubbo接口的时候,有些接口参数类型是JavaBean类型的数据,在整理的时候又想直接将JavaBean参数直接以默认的json格式整理,于是想到如何将javaBean的默认值 直接转换成为 Json格式的数据,避免自己手动去拼写json字符串。

此段代码还有值得优化的地方

暂时只支持Java基本数据类型的转换,不支持javaBean中包含其他javaBean对象变量的转换、也不支持List/Map等类型的转换,后期有空想办法优化,大家如果有优化好的代码也可以拿出来分享

废话不多说,直接上代码

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

package com.up.util.tools;

import com.google.gson.Gson;

import java.lang.reflect.Field;

import java.lang.reflect.Method;

import java.util.Date;

import java.util.HashMap;

import java.util.Map;

 

/**

  * Created by *** on 2017-3-29

  * TIME 11:07.

  */

public class JavaBeanToJson {

     public static String toJson(Class clazz) throws Exception {

         Gson gson = new Gson();

         String result = "" ;

         if (clazz.equals(Map. class )) {

             result = clazz.getName() + "\t" + gson.toJson( new HashMap<>());

         } else {

             Object object = clazz.newInstance();

             object = getBean(object);

             result = clazz.getName() + "\t" + gson.toJson(object);

         }

         return result;

     }

 

     private static <T> Object getBean(T object) throws Exception {

         Class<?> classType = object.getClass();

         //SqlRowSet srs = jdbcTemplate.queryForRowSet(sql);

         Field[] fields = classType.getDeclaredFields(); //得到对象中的字段

         //每次循环时,重新实例化一个与传过来的对象类型一样的对象

         T objectCopy = (T) classType.getConstructor( new Class[]{}).newInstance( new Object[]{});

         for ( int i = 0 ; i < fields.length; i++) {

             Field field = fields[i];

             String fieldName = field.getName();

             Object value = null ;

             //根据字段类型决定结果集中使用哪种get方法从数据中取到数据

             if (field.getType().equals(String. class )) {

                 value = "" ;

             } else if (field.getType().equals( int . class ) || field.getType().equals(Integer. class )) {

                 value = new Integer( 0 );

             } else if (field.getType().equals( double . class ) || field.getType().equals(Double. class )) {

                 value = new Double( 0 );

             } else if (field.getType().equals( long . class ) || field.getType().equals(Long. class )) {

                 value = new Long( 0 );

             } else if (field.getType().equals(Date. class )) {

                 value = new Date();

             } else if (field.getType().equals(Object. class )) {

                 value = new Object();

             }

             // 获得属性的首字母并转换为大写,与setXXX对应

             String firstLetter = fieldName.substring( 0 , 1 ).toUpperCase();

             String setMethodName = "set" + firstLetter

                     + fieldName.substring( 1 );

             if (fieldName.equals( "serialVersionUID" )) {

                 continue ;

             }

             Method setMethod = classType.getMethod(setMethodName,

                     new Class[]{field.getType()});

             setMethod.invoke(objectCopy, new Object[]{value}); //调用对象的setXXX方法

         }

         return objectCopy;

     }

}

javaBean对象和Json格式字符串相互转换

一般前后端开发都是使用json格式的字符串进行交互的,所以javaBean对象转化为json格式字符串和json格式字符串转化为javaBean对象显的很有必要。

下面介绍两种方法:

一.使用Jackson工具类

1.pom依赖

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

<!--jackson 2.x版本依赖-->

< dependency >

    < groupId >com.fasterxml.jackson.core</ groupId >

    < artifactId >jackson-annotations</ artifactId >

    < version >2.8.1</ version >

</ dependency >

< dependency >

    < groupId >com.fasterxml.jackson.core</ groupId >

    < artifactId >jackson-core</ artifactId >

    < version >2.8.6</ version >

</ dependency >

< dependency >

    < groupId >com.fasterxml.jackson.core</ groupId >

    < artifactId >jackson-databind</ artifactId >

    < version >2.8.6</ version >

</ dependency >

<!--junit依赖-->

< dependency >

    < groupId >junit</ groupId >

    < artifactId >junit</ artifactId >

    < version >4.12</ version >

</ dependency >

2.程序代码

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

package com.john.json; 

import com.fasterxml.jackson.databind.ObjectMapper;

import org.junit.Test; 

import java.io.IOException; 

public class TestJackson {

 

    @Test

    public void testObjAndJson() throws IOException { 

        Dog dog = new Dog();

        dog.setName( "樱桃" );

        dog.setAge( 1 );

        dog.setFood( "小米" );

 

        //创建Jackson高级对象

        ObjectMapper mapper = new ObjectMapper();

 

        //对象转换为对应的json格式字符串

        String json = mapper.writeValueAsString(dog); 

        System.out.println(json);

 

        //json格式字符串转换为对应的对象

        Dog dogBack = mapper.readValue(json, Dog. class ); 

        System.out.println(dogBack.getName()+ "--" +dogBack.getAge()+ "--" +dogBack.getFood()); 

    }

}

二.使用Gson工具类

1.pom依赖

?

1

2

3

4

5

6

7

8

9

10

11

12

<!--gson依赖-->

< dependency >

    < groupId >com.google.code.gson</ groupId >

    < artifactId >gson</ artifactId >

    < version >2.2.4</ version >

</ dependency >

<!--junit依赖-->

< dependency >

    < groupId >junit</ groupId >

    < artifactId >junit</ artifactId >

    < version >4.12</ version >

</ dependency >

2.程序代码

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

package com.john.json; 

import com.google.gson.Gson;

import org.junit.Test; 

public class TestGson {

 

    @Test

    public void testObjAndJson() { 

        Dog dog = new Dog();

        dog.setName( "妞妞" );

        dog.setAge( 3 );

        dog.setFood( "大米" );

 

        //创建gson对象

        Gson gson = new Gson();

 

        //对象转化为对应的json格式字符串

        String dogJson = gson.toJson(dog); 

        System.out.println(dogJson);

 

        //json格式字符串转换为对应的对象

        Dog dogBack = gson.fromJson(dogJson, Dog. class ); 

        System.out.println(dogBack.getName()+ "--" +dogBack.getAge()+ "--" +dogBack.getFood());

    } 

}

以上为个人经验,希望能给大家一个参考,也希望大家多多支持。

原文链接:https://blog.csdn.net/qi_lin7/article/details/68068151

查看更多关于给JavaBean赋默认值并且转Json字符串的实例的详细内容...

  阅读:20次