服务器之家:专注于服务器技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|JAVA教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|JavaScript|

服务器之家 - 编程语言 - JAVA教程 - 基于JSON和java对象的互转方法

基于JSON和java对象的互转方法

2020-12-28 09:38firs大风吹 JAVA教程

下面小编就为大家带来一篇基于JSON和java对象的互转方法。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧

先说下我自己的理解,一般而言,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, '}');
  } 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, ']');
  } 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, ']');
  } 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, '}');
  } 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, ']');
  } 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 '"':
    sb.append("\\\"");
    break;
   case '\\':
    sb.append("\\\\");
    break;
   case '\b':
    sb.append("\\b");
    break;
   case '\f':
    sb.append("\\f");
    break;
   case '\n':
    sb.append("\\n");
    break;
   case '\r':
    sb.append("\\r");
    break;
   case '\t':
    sb.append("\\t");
    break;
   case '/':
    sb.append("\\/");
    break;
   default:
    if (ch >= '\u0000' && ch <= '\u001F') {
     String ss = Integer.toHexString(ch);
     sb.append("\\u");
     for (int k = 0; k < 4 - ss.length(); k++) {
      sb.append('0');
     }
     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"));
  
  
 }
}

再来聊聊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;
 }
 
}

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

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

以上这篇基于JSON和java对象的互转方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持服务器之家。

原文链接:http://www.cnblogs.com/sundaymorning/archive/2017/09/06/7482721.html

延伸 · 阅读

精彩推荐