首先自己编写一个类DDAL
public class DDAL {
private int a;
private String b;
public DDAL(int a,String b){
this.a = a;
this.b = b;
}
public int getA() {
return a;
}
public String getB() {
return b;
}
@Override
public String toString(){
return "DDAL [a=" + a + ", b=" + b + "]";
}
}
在主函数实现:
import com.alibaba.fastjson.TypeReference;
import com.alibaba.fastjson.JSON;
public class Jstet {
public static void main(String[] args) {
String s = "{\"a\":1,\"b\":\"success\" }";
DDAL characterInfo = JSON.parseObject(s, new TypeReference<DDAL>() {});
System.out.println(characterInfo.toString());
System.out.println(characterInfo.getA());
System.out.println(characterInfo.getB());
}
}
其中String s = "{\"a\":1,\"b\":\"success\" }";
是Json数据的String 传输格式。
Java中Json 转 String
//创建JSONObject对象
JSONObject json = new JSONObject();
//向json中添加数据
json.put("username", "wanglihong");
json.put("height", 12.5);
json.put("age", 24);
//创建JSONArray数组,并将json添加到数组
JSONArray array = new JSONArray();
array.put(json);
//转换为字符串
String jsonStr = array.toString()
System.out.println(jsonStr);
输出结果[{"username":"wanglihong","height":12.5,"age":24}]
JSONObject转换string方法实例
public class User {
String id;
String name;
int age;
Book book;
}
public class Book {
String id;
String name;
}
public class Json {
public static void main(String[] args) {
Book book = new Book();
book.setId("111");
book.setName("语文");
User u = new User();
u.setId("002");
u.setName("xim");
u.setBook(book);
JSONObject jo = JSONObject.fromObject(u);
System.out.println(jo);
}
}
输出结果{"age":0,"book":{"id":"111","name":"语文"},"id":"002","name":"xim"}