AI智能
改变未来

工具-JSON


简介

  • JSON
    JavaScript Object Notation JS对象简谱,是一种轻量级的数据交换格式。

对象格式

数组格式

案例

{\"name\":\"何同学\",\"age\":18,\"pengyou\":[\"张三\",\"李四\",\"王二\",\"麻子\",{\"name\":\"野马老师\",\"info\":\"像匹野马一样狂奔在技术钻研的道路上\"}],\"heihei\":{\"name\":\"大长刀\",\"length\":\"40m\"}}

Gson 和 FastJson

  • 测试类BOOK
public class BOOK {private String id;private String name;private String info;public BOOK() {}public BOOK(String id, String name, String info) {this.id = id;this.name = name;this.info = info;}public String getId() {return id;}public void setId(String id) {this.id = id;}public String getName() {return name;}public void setName(String name) {this.name = name;}public String getInfo() {return info;}public void setInfo(String info) {this.info = info;}@Overridepublic boolean equals(Object o) {if (this == o) return true;if (o == null || getClass() != o.getClass()) return false;BOOK book = (BOOK) o;return Objects.equals(id, book.id) &&Objects.equals(name, book.name) &&Objects.equals(info, book.info);}@Overridepublic int hashCode() {return Objects.hash(id, name, info);}@Overridepublic String toString() {return \"BOOK{\" +\"id=\'\" + id + \'\\\'\' +\", name=\'\" + name + \'\\\'\' +\", info=\'\" + info + \'\\\'\' +\'}\';}}
  • Gson(类转JSON)
//BOOK对象转JSON语言BOOK book = new BOOK(\"100\",\"一本书\",\"我是一本书\");//1.    创建Gson对象Gson g = new Gson();//2.    转换String s = g.toJson(book);
  • Gson(JSON 转类)
//{\"id\":\"100\",\"name\":\"一本书\",\"info\":\"我是一本书\"}转BOOK对象//1.    创建Gson对象Gson g = new Gson();//2.    转换BOOK book = g.fromJson(\"{\\\"id\\\":\\\"100\\\",\\\"name\\\":\\\"一本书\\\",\\\"info\\\":\\\"我是一本书\\\"}\", BOOK.class);
  • FastJson(类转JSON)
BOOK book = new BOOK(\"111\",\"我也是一本书\",\"这也一本书\");//1.    转换String s = JSON.toJSONString(book);
  • FastJson (JSON转类)
//{\"id\":\"111\",\"info\":\"这也一本书\",\"name\":\"我也是一本书\"}//1.    转对象BOOK book = JSON.parseObject(\"{\\\"id\\\":\\\"111\\\",\\\"info\\\":\\\"这也一本书\\\",\\\"name\\\":\\\"我也是一本书\\\"}\", BOOK.class);//2.    转数组[\"一\",\"二\",\"三\"]List<String> strings = JSON.parseArray(\"[\\\"一\\\",\\\"二\\\",\\\"三\\\"]\", String.class);
赞(0) 打赏
未经允许不得转载:爱站程序员基地 » 工具-JSON