Json基本语法以及Json数据和Java对象转换

1.基本语法

 // 定义josn
    var json = {
        "name":"zhangsan",
        "age":23,
        "addr":["北京","上海","重庆"]
    };

    //获取josn
    alert(json.addr);

2.Json数据和Java对象转换

1.请求数据:json字符串转为java对象  浏览器发送给Java
   String jsonstr =JSON.toJSONString(obj);
2.响应数据:java对象转为json字符串  java发送给浏览器
   User user = JSON.parseObject(jsonstr,User.class);

3.引入fastjson坐标


    com.alibaba
    fastjson
    1.2.62

实体类(实现get/set方法,实现toString方法)

package com.itheima.json;

public class User {
    private Integer id ;
    private String username;
    private String password;

    //alt+insert

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", username='" + username + '\'' +
                ", password='" + password + '\'' +
                '}';
    }
}

将一个Java对象转为json字符串

 //1.将一个Java对象转为json字符串
        User user = new User();
        user.setId(1);
        user.setUsername("张三");
        user.setPassword("123456");
        String jsonString = JSON.toJSONString(user);//{"id":1,"password":"123456","username":"张三"}

将json字符串转为Java对象

//2.将json字符串转为Java对象

        User parseObject = JSON.parseObject("{\"id\":1,\"password\":\"123456\",\"username\":\"张三\"}", User.class);
        System.out.println(parseObject);

全部代码

package com.itheima.json;

import com.alibaba.fastjson.JSON;

public class FastJsonDemo {

    public static void main(String[] args) {
        /*
        jso数据与java对象相互转换
        1.请求数据:json字符串转为java对象  浏览器发送给Java
          String jsonstr =JSON.toJSONString(obj);
        2.响应数据:java对象转为json字符串  java发送给浏览器
          User user = JSON.parseObject(jsonstr,User.class);
        */

        //1.将一个Java对象转为json字符串
        User user = new User();
        user.setId(1);
        user.setUsername("张三");
        user.setPassword("123456");
        String jsonString = JSON.toJSONString(user);//{"id":1,"password":"123456","username":"张三"}

        System.out.println(jsonString);
        //2.将json字符串转为Java对象

        User parseObject = JSON.parseObject("{\"id\":1,\"password\":\"123456\",\"username\":\"张三\"}", User.class);
        System.out.println(parseObject);
    }
}

实现效果

Json基本语法以及Json数据和Java对象转换_第1张图片

 

你可能感兴趣的:(AJAX,json)