JSON字符串和JSON对象的相互转换

一、js

1.1、JSON对象转JSON字符串

var jsonObj = {"stuName":"tom","stuAge":20};
var jsonStr = JSON.stringify(jsonObj);

console.log(typeof jsonObj); // object
console.log(typeof jsonStr); // string

1.2、JSON字符串转JSON对象

jsonObj = JSON.parse(jsonStr);
console.log(jsonObj); // {stuName: "tom", stuAge: 20}

二、java

  • 在java完成JSON字符串和JSON对象的转换,需要使用gson的jar包
  • 实例化gson对象,以及声明与所需解析JSON格式对应的pojo类
    • Gson gson = new Gson();

2.1、JSON字符串转JSON对象

// gson.fromJson(String , Object.class); String ->JSON
 Student student = gson.fromJson(str, Student.class);
 System.out.println("student = " + student);

2.2、JSON对象转JSON字符串

   // gson.toJson(Object);  JSON -> String
  String studentStr = gson.toJson(student);
  System.out.println("studentStr = " + studentStr);

你可能感兴趣的:(javaWeb,json,前端,javascript)