Home Java javaTutorial Detailed explanation of sample code for converting Java objects to JSON

Detailed explanation of sample code for converting Java objects to JSON

Sep 06, 2017 am 09:48 AM
java javascript json

先说下我自己的理解,一般而言,JSON字符串要转为java对象需要自己写一个跟JSON一模一样的实体类bean,然后用bean.class作为参数传给对应的方法,实现转化成功。

上述这种方法太麻烦了。其实有一种东西叫jsonObject可以直接不用新建实体类bean,而实现转化,先说org.json.JSONObject这个JSONObject,贴上代码:

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

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

93

94

95

96

97

98

99

100

101

102

103

104

105

106

107

108

109

110

111

112

113

114

115

116

117

118

119

120

121

122

123

124

125

126

127

128

129

130

131

132

133

134

135

136

137

138

139

140

141

142

143

144

145

146

147

148

149

150

151

152

153

154

155

156

157

158

159

160

161

162

163

164

165

166

167

168

169

170

171

172

173

174

175

176

177

178

179

180

181

182

183

184

185

186

187

188

189

190

191

192

193

194

195

196

197

198

199

200

201

202

203

204

205

206

207

208

209

210

211

212

213

214

215

216

217

218

219

220

221

222

223

224

225

226

227

228

229

230

231

232

233

234

235

236

237

238

239

240

241

242

243

244

245

246

247

248

249

250

251

252

253

254

255

256

257

258

259

260

261

262

263

264

265

266

267

268

269

270

271

272

273

274

275

276

277

278

279

280

281

282

import java.beans.IntrospectionException;

import java.beans.Introspector;

import java.beans.PropertyDescriptor;

import java.util.ArrayList;

import java.util.HashMap;

import java.util.Iterator;

import java.util.List;

import java.util.Map;

import java.util.Set;

 

import org.json.JSONObject;

 

/**

* Json工具类,实现了实体类和Json数据格式之间的互转功能 使用实例:<br>

*/

public class JsonUtils {

    /**

     * 将一个实体类对象转换成Json数据格式

     *

     * @param bean

     *            需要转换的实体类对象

     * @return 转换后的Json格式字符串

     */

    private static String beanToJson(Object bean) {

        StringBuilder json = new StringBuilder();

        json.append("{");

        PropertyDescriptor[] props = null;

        try {

            props = Introspector.getBeanInfo(bean.getClass(), Object.class)

                    .getPropertyDescriptors();

        } catch (IntrospectionException e) {

        }

        if (props != null) {

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

                try {

                    String name = objToJson(props[i].getName());

                    String value = objToJson(props[i].getReadMethod()

                            .invoke(bean));

                    json.append(name);

                    json.append(":");

                    json.append(value);

                    json.append(",");

                } catch (Exception e) {

                }

            }

            json.setCharAt(json.length() - 1, &#39;}&#39;);

        } else {

            json.append("}");

        }

        return json.toString();

    }

 

 

    /**

     * 将一个List对象转换成Json数据格式返回

     *

     * @param list

     *            需要进行转换的List对象

     * @return 转换后的Json数据格式字符串

     */

    private static String listToJson(List<?> list) {

        StringBuilder json = new StringBuilder();

        json.append("[");

        if (list != null && list.size() > 0) {

            for (Object obj : list) {

                json.append(objToJson(obj));

                json.append(",");

            }

            json.setCharAt(json.length() - 1, &#39;]&#39;);

        } else {

            json.append("]");

        }

        return json.toString();

    }

 

    /**

     * 将一个对象数组转换成Json数据格式返回

     *

     * @param array

     *            需要进行转换的数组对象

     * @return 转换后的Json数据格式字符串

     */

    private static String arrayToJson(Object[] array) {

        StringBuilder json = new StringBuilder();

        json.append("[");

        if (array != null && array.length > 0) {

            for (Object obj : array) {

                json.append(objToJson(obj));

                json.append(",");

            }

            json.setCharAt(json.length() - 1, &#39;]&#39;);

        } else {

            json.append("]");

        }

        return json.toString();

    }

 

    /**

     * 将一个Map对象转换成Json数据格式返回

     *

     * @param map

     *            需要进行转换的Map对象

     * @return 转换后的Json数据格式字符串

     */

    private static String mapToJson(Map<?, ?> map) {

        StringBuilder json = new StringBuilder();

        json.append("{");

        if (map != null && map.size() > 0) {

            for (Object key : map.keySet()) {

                json.append(objToJson(key));

                json.append(":");

                json.append(objToJson(map.get(key)));

                json.append(",");

            }

            json.setCharAt(json.length() - 1, &#39;}&#39;);

        } else {

            json.append("}");

        }

        return json.toString();

    }

 

    /**

     * 将一个Set对象转换成Json数据格式返回

     *

     * @param set

     *            需要进行转换的Set对象

     * @return 转换后的Json数据格式字符串

     */

    private static String setToJson(Set<?> set) {

        StringBuilder json = new StringBuilder();

        json.append("[");

        if (set != null && set.size() > 0) {

            for (Object obj : set) {

                json.append(objToJson(obj));

                json.append(",");

            }

            json.setCharAt(json.length() - 1, &#39;]&#39;);

        } else {

            json.append("]");

        }

        return json.toString();

    }

 

    private static String stringToJson(String s) {

        if (s == null) {

            return "";

        }

        StringBuilder sb = new StringBuilder();

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

            char ch = s.charAt(i);

            switch (ch) {

            case &#39;"&#39;:

                sb.append("\\\"");

                break;

            case &#39;\\&#39;:

                sb.append("\\\\");

                break;

            case &#39;\b&#39;:

                sb.append("\\b");

                break;

            case &#39;\f&#39;:

                sb.append("\\f");

                break;

            case &#39;\n&#39;:

                sb.append("\\n");

                break;

            case &#39;\r&#39;:

                sb.append("\\r");

                break;

            case &#39;\t&#39;:

                sb.append("\\t");

                break;

            case &#39;/&#39;:

                sb.append("\\/");

                break;

            default:

                if (ch >= &#39;\u0000&#39; && ch <= &#39;\u001F&#39;) {

                    String ss = Integer.toHexString(ch);

                    sb.append("\\u");

                    for (int k = 0; k < 4 - ss.length(); k++) {

                        sb.append(&#39;0&#39;);

                    }

                    sb.append(ss.toUpperCase());

                } else {

                    sb.append(ch);

                }

            }

        }

        return sb.toString();

    }

 

    public static String objToJson(Object obj) {

        StringBuilder json = new StringBuilder();

        if (obj == null) {

            json.append("\"\"");

        } else if (obj instanceof Number) {

            Number num = (Number)obj;

            json.append(num.toString());

        } else if (obj instanceof Boolean) {

            Boolean bl = (Boolean)obj;

            json.append(bl.toString());

        } else if (obj instanceof String) {

            json.append("\"").append(stringToJson(obj.toString())).append("\"");

        } else if (obj instanceof Object[]) {

            json.append(arrayToJson((Object[]) obj));

        } else if (obj instanceof List) {

            json.append(listToJson((List) obj));

        } else if (obj instanceof Map) {

            json.append(mapToJson((Map) obj));

        } else if (obj instanceof Set) {

            json.append(setToJson((Set) obj));

        } else {

            json.append(beanToJson(obj));

        }

        return json.toString();

    }

     

    /**

      * @Title: json2Map

      * @Creater: chencc <br>

      * @Date: 2011-3-28 <br>

      * @Description: TODO转化json2map

      * @param @param jsonString

      * @param @return

      * @return Map<String,Object>

      * @throws

     */

    @SuppressWarnings("unchecked")

    public static Map<String, Object> json2Map(String jsonString) {

         

        Map<String, Object> map = new HashMap<String, Object>();

        try {

            if(null != jsonString && !"".equals(jsonString)){

                JSONObject jsonObject = new JSONObject(jsonString);

             

                Iterator keyIter = jsonObject.keys();

                String key = "";

                Object value = null;

             

                while (keyIter.hasNext()) {

                    key = (String) keyIter.next();

                    value = jsonObject.get(key);

                    map.put(key, value);

                }

            }

        } catch (Exception e) {

            e.printStackTrace();

        }

        return map;

    }

     

    //测试方法

    public static void main(String[] args) {

        Map<String,Object> params = new HashMap<String,Object>();

        params.put("callId123", Integer.valueOf(1000));

        Map retMap = new HashMap();

        retMap.put("params", params);

        retMap.put("result", true);

        List ls = new ArrayList();

        ls.add(new HashMap());

        ls.add("hello world!!");

        ls.add(new String[4]);

        retMap.put("list", ls);

         

        String[] strArray = new String[10];

        strArray[1]="first";

        strArray[2]="2";

        strArray[3]="3";

        System.out.println("Boolean:"+JsonUtils.objToJson(true));

        System.out.println("Number:"+JsonUtils.objToJson(23.3));

        System.out.println("String:"+JsonUtils.objToJson("sdhfsjdgksdlkjfk\"sd,!#%$^&*#(*@&*%&*$fsdfsdfsdf"));

        System.out.println("Map :"+JsonUtils.objToJson(retMap));

        System.out.println("List:"+JsonUtils.objToJson(ls));

        System.out.println("Array:"+JsonUtils.objToJson(strArray));

         

        String json = JsonUtils.objToJson(retMap);

        Map r = JsonUtils.json2Map(json);

        System.out.println(r.get("callId123"));

         

         

    }

}

Copy after login

再来聊聊net.sf.json.JSONObject这个JSONObject,代码如下

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

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

93

94

95

96

97

98

99

100

101

102

103

104

105

106

107

108

109

110

111

112

113

114

115

116

117

118

119

120

121

122

123

124

125

126

127

128

129

130

131

132

133

134

135

136

137

138

139

140

141

142

143

144

145

146

147

148

149

150

151

152

153

154

155

156

157

158

159

160

161

162

163

164

165

import java.io.IOException;

import java.text.SimpleDateFormat;

import java.util.ArrayList;

import java.util.HashMap;

import java.util.LinkedHashMap;

import java.util.List;

import java.util.Map;

import java.util.TimeZone;

 

import net.sf.json.JSONArray;

import net.sf.json.JSONObject;

import net.sf.json.JsonConfig;

import net.sf.json.util.CycleDetectionStrategy;

import net.sf.json.util.PropertyFilter;

 

import com.fasterxml.jackson.annotation.JsonInclude.Include;

import com.fasterxml.jackson.databind.DeserializationFeature;

import com.fasterxml.jackson.databind.ObjectMapper;

 

public class JsonUtil {

     

     

    private static ObjectMapper objectMapper = null;

    /**

     * JSON初始化

     */

    static {

        objectMapper = new ObjectMapper(); 

        //设置为中国上海时区 

        objectMapper.setTimeZone(TimeZone.getTimeZone("GMT+8")); 

        //空值不序列化 

        objectMapper.setSerializationInclusion(Include.NON_NULL); 

        //反序列化时,属性不存在的兼容处理 

        objectMapper.getDeserializationConfig().withoutFeatures(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES); 

        //序列化时,日期的统一格式 

        objectMapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")); 

 

        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); 

         

    }

     

     

    /**

     * 把对象转换成为Json字符串

     *

     * @param obj

     * @return

     */

    public static String convertObjectToJson(Object obj) {

        if (obj == null) {

//                throw new IllegalArgumentException("对象参数不能为空。");

            return null;

        }

        try {

            return objectMapper.writeValueAsString(obj);

 

        catch (IOException e) {

            e.printStackTrace();

        }

        return null;

 

    }

    /**

     *  把json字符串转成Object对象

     * @param jsonString

     * @return T

     */

    public static <T> T parseJsonToObject(String jsonString, Class<T> valueType) {

         

        if(jsonString == null || "".equals((jsonString))){

            return null;

        }

        try {

            return objectMapper.readValue(jsonString, valueType);

        } catch (Exception e) {

            e.printStackTrace();

        }

        return null;

    }

    /**

     *  把json字符串转成List对象

     * @param jsonString

     * @return List<T>

     */

    @SuppressWarnings("unchecked")

    public static <T> List<T> parseJsonToList(String jsonString,Class<T> valueType) {

         

        if(jsonString == null || "".equals((jsonString))){

            return null;

        }

         

        List<T> result = new ArrayList<T>();

        try {

            List<LinkedHashMap<Object, Object>> list = objectMapper.readValue(jsonString, List.class);

             

            for (LinkedHashMap<Object, Object> map : list) {

                 

                String jsonStr = convertObjectToJson(map);

                 

                T t = parseJsonToObject(jsonStr, valueType);

                 

                result.add(t);

            }

        } catch (Exception e) {

            e.printStackTrace();

        }

        return result;

    }

    /**

     * JSON处理含有嵌套关系对象,避免出现异常:net.sf.json.JSONException: There is a cycle in the hierarchy的方法

     * 注意:这样获得到的字符串中,引起嵌套循环的属性会置为null

     *

     * @param obj

     * @return

     */

    public static JSONObject getJsonObject(Object obj) {

 

        JsonConfig jsonConfig = new JsonConfig();

        jsonConfig.setCycleDetectionStrategy(CycleDetectionStrategy.LENIENT);

        jsonConfig.setJsonPropertyFilter(new PropertyFilter() {

             

            @Override

            public boolean apply(Object source, String name, Object value) {

                if(value==null){

                    return true;

                }

                return false;

            }

        });

        return JSONObject.fromObject(obj, jsonConfig);

    }

    /**

     * JSON处理含有嵌套关系对象,避免出现异常:net.sf.json.JSONException: There is a cycle in the hierarchy的方法

 

     * 注意:这样获得到的字符串中,引起嵌套循环的属性会置为null

     *

     * @param obj

     * @return

     */

    public static JSONArray getJsonArray(Object obj) {

 

        JsonConfig jsonConfig = new JsonConfig();

        jsonConfig.setCycleDetectionStrategy(CycleDetectionStrategy.LENIENT);

 

        return JSONArray.fromObject(obj, jsonConfig);

    }

    /**

     * 解析JSON字符串成一个MAP

     *

     * @param jsonStr json字符串,格式如: {dictTable:"BM_XB",groupValue:"分组值"}

     * @return

     */

    public static Map<String, Object> parseJsonStr(String jsonStr) {

 

        Map<String, Object> result = new HashMap<String, Object>();

 

        JSONObject jsonObj = JsonUtil.getJsonObject(jsonStr);

 

        for (Object key : jsonObj.keySet()) {

            result.put((String) key, jsonObj.get(key));

        }

        return result;

    }

 

}

Copy after login

总结:net.sf.json.JSONObject这个属于json-lib这个老牌的系列,依赖的包超级多,commons的lang、logging、beanutils、collections等组件都有。

而org.json则相对来说依赖的包少一些,速度和性能方面没有怎么进行测试。

The above is the detailed content of Detailed explanation of sample code for converting Java objects to JSON. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Perfect Number in Java Perfect Number in Java Aug 30, 2024 pm 04:28 PM

Guide to Perfect Number in Java. Here we discuss the Definition, How to check Perfect number in Java?, examples with code implementation.

Weka in Java Weka in Java Aug 30, 2024 pm 04:28 PM

Guide to Weka in Java. Here we discuss the Introduction, how to use weka java, the type of platform, and advantages with examples.

Smith Number in Java Smith Number in Java Aug 30, 2024 pm 04:28 PM

Guide to Smith Number in Java. Here we discuss the Definition, How to check smith number in Java? example with code implementation.

Java Spring Interview Questions Java Spring Interview Questions Aug 30, 2024 pm 04:29 PM

In this article, we have kept the most asked Java Spring Interview Questions with their detailed answers. So that you can crack the interview.

Break or return from Java 8 stream forEach? Break or return from Java 8 stream forEach? Feb 07, 2025 pm 12:09 PM

Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

TimeStamp to Date in Java TimeStamp to Date in Java Aug 30, 2024 pm 04:28 PM

Guide to TimeStamp to Date in Java. Here we also discuss the introduction and how to convert timestamp to date in java along with examples.

Java Program to Find the Volume of Capsule Java Program to Find the Volume of Capsule Feb 07, 2025 am 11:37 AM

Capsules are three-dimensional geometric figures, composed of a cylinder and a hemisphere at both ends. The volume of the capsule can be calculated by adding the volume of the cylinder and the volume of the hemisphere at both ends. This tutorial will discuss how to calculate the volume of a given capsule in Java using different methods. Capsule volume formula The formula for capsule volume is as follows: Capsule volume = Cylindrical volume Volume Two hemisphere volume in, r: The radius of the hemisphere. h: The height of the cylinder (excluding the hemisphere). Example 1 enter Radius = 5 units Height = 10 units Output Volume = 1570.8 cubic units explain Calculate volume using formula: Volume = π × r2 × h (4

Create the Future: Java Programming for Absolute Beginners Create the Future: Java Programming for Absolute Beginners Oct 13, 2024 pm 01:32 PM

Java is a popular programming language that can be learned by both beginners and experienced developers. This tutorial starts with basic concepts and progresses through advanced topics. After installing the Java Development Kit, you can practice programming by creating a simple "Hello, World!" program. After you understand the code, use the command prompt to compile and run the program, and "Hello, World!" will be output on the console. Learning Java starts your programming journey, and as your mastery deepens, you can create more complex applications.

See all articles