来源:java 将字符串转为对象,对应到实体类//转成map_murongyuyao的博客-CSDN博客_java 字符串转对象
maven
<!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.62</version>
</dependency>
主方法
package test;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
public class test1 {
public static void main(String[] args){
String str = "{\"id\":\"1\",\"name\":\"吴彦祖\",\"age\":\"46\"}";
//将字符串转为json数据
JSONObject json = JSONObject.parseObject(str);
System.out.println(json.toJSONString());
//json数据按key取值
System.out.println(json.getString("name"));
System.out.println(json.getString("age"));
//将json数据转换为java对象/实体类
UserBean user = JSON.parseObject(str, UserBean.class);
System.out.println(user.toString());
//将字符串转成map集合
Map<String, String> maps = JSON.parseObject(hashMap, HashMap.class);
System.out.println(maps)
//将java对象/实体类转换为json数据
JSONObject jsonUser = (JSONObject) JSONObject.toJSON(user);
System.out.println("jsonUser:"+jsonUser);
}
}
实体类:
package test;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class UserBean {
private String name;
private String id;
private String age;
}
json合并
import com.alibaba.fastjson.JSONObject;
public class test1 {
public static void main(String[] args){
JSONObject json1 = new JSONObject();
JSONObject json2 = new JSONObject();
json1.put("name", "吴彦祖");
json1.put("age", "46");
System.out.println(json1.toString());
json2.put("address", "香港");
json2.put("profession", "演员");
System.out.println(json2.toString());
JSONObject jsonMerge = new JSONObject();
jsonMerge.putAll(json1);
jsonMerge.putAll(json2);
System.out.println("合并后:"+jsonMerge.toString());
}
}