对象json格式怎么转换/
时间: 2023-12-27 14:23:48 浏览: 75
如何把一个对象转换为JSON
3星 · 编辑精心推荐
以下是JS对象与JSON字符串之间的转换方法:
1.将JS对象转换为JSON字符串
```javascript
let obj = {name: "John", age: 30, city: "New York"};
let jsonStr = JSON.stringify(obj);
console.log(jsonStr); // 输出:{"name":"John","age":30,"city":"New York"}
```
2.将JSON字符串转换为JS对象
```javascript
let jsonStr = '{"name":"John","age":30,"city":"New York"}';
let obj = JSON.parse(jsonStr);
console.log(obj); // 输出:{name: "John", age: 30, city: "New York"}
```
3.将Java对象转换为JSON字符串
```java
import com.alibaba.fastjson.JSON;
public class Test {
public static void main(String[] args) {
Person person = new Person("John", 30, "New York");
String jsonStr = JSON.toJSONString(person);
System.out.println(jsonStr); // 输出:{"age":30,"city":"New York","name":"John"}
}
}
class Person {
private String name;
private int age;
private String city;
public Person(String name, int age, String city) {
this.name = name;
this.age = age;
this.city = city;
}
// 省略getter和setter方法
}
```
4.将JSON字符串转换为Java对象
```java
import com.alibaba.fastjson.JSON;
public class Test {
public static void main(String[] args) {
String jsonStr = "{\"age\":30,\"city\":\"New York\",\"name\":\"John\"}";
Person person = JSON.parseObject(jsonStr, Person.class);
System.out.println(person.getName()); // 输出:John
}
}
class Person {
private String name;
private int age;
private String city;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
}
```
阅读全文