Json

Posted inspire0x001

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Json相关的知识,希望对你有一定的参考价值。

一.Json

1.什么是Json?

Json是我们传输数据时用到的一种数据格式。还有其他的传输数据的格式,如 纯文本,XML等

2.如何构建json数据?

(1).使用org.json.JSONObject 构建Json数据。

 

/**
     * 使用JsonObject构建Json数据
     */
    public static void JsonObject1() {
        JSONObject jsonObject=new JSONObject();
        Object obj=null;
        try {
            jsonObject.put("id",1);
            jsonObject.put("name","小强");
            jsonObject.put("age",20);
            jsonObject.put("major",new java.lang.String[]{"aa","bb"});
            jsonObject.put("car",obj);
            jsonObject.put("isGood",true);
            System.out.println(jsonObject.toString());
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

 

(2).使用Hashmap构建Json数据

/**
     * 使用Hashmap构建Json数据
     */
    public static void JsonObject2(){
        Map<String,Object> map=new HashMap<String, Object>();
        Object obj=null;
        map.put("id",1);
        map.put("name","小强");
        map.put("age",20);
        map.put("major",new String[]{"aa","bb"});
        map.put("car",obj);
        map.put("isGood",true);
        JSONObject jsonObject=new JSONObject(map);//通过构造方法,把map放进去
        System.out.println(jsonObject.toString());

    }

(3).javaBean构建json数据

我们有一个JavaBean

public class User {
    private int id;private String name;
    private int age;
    private String birthday;
    private String[] major;
    private Object car;
    private boolean have;
    private Date time;

    public int getId() {
        return id;
    }

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

    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 getBirthday() {
        return birthday;
    }

    public void setBirthday(String birthday) {
        this.birthday = birthday;
    }

    public String[] getMajor() {
        return major;
    }

    public void setMajor(String[] major) {
        this.major = major;
    }

    public Object getCar() {
        return car;
    }

    public void setCar(Object car) {
        this.car = car;
    }

    public boolean isHave() {
        return have;
    }

    public Date getTime() {
        return time;
    }

    public void setTime(Date time) {
        this.time = time;
    }

    public void setHave(boolean have) {
        this.have = have;
    }


    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", name=‘" + name + \‘ +
                ", age=" + age +
                ", birthday=‘" + birthday + \‘ +
                ", major=" + Arrays.toString(major) +
                ", car=" + car +
                ", have=" + have +
                };
    }
}

 

/**
     * javaBean构建json数据
     */
    public static void JsonObject3(){
        User user=new User();
        user.setId(1);
        user.setName("aa");
        user.setAge(20);
        user.setBirthday("2011-2-22");
        user.setCar(null);
        user.setHave(true);
        user.setMajor(new String[]{"aa","bb"});
        JSONObject jsonObject=new JSONObject(user);//通过构造方法把对象放进去
        System.out.println(jsonObject);
    }

3.如何读取一个Json数据

我们有一个Json格式的数据文件

{
  "major":["aa","bb"],
  "isGood":true,
  "name":"小强",
  "id":1,
  "age":20
}

读取这个文件,并输出里面的信息

public static void main(String[] args) throws IOException, JSONException {
        File file=new File(ReadJsonSample.class.getResource("/user.json").getFile());
        String content= FileUtils.readFileToString(file);
        JSONObject jsonObject=new JSONObject(content);
        System.out.println(jsonObject.getInt("id"));
        System.out.println(jsonObject.getString("name"));
        System.out.println(jsonObject.getInt("age"));
    }

二.Gson

1.用com.google.gson.Gson构建gson数据

public static void Gson1(){
        User user=new User();
        user.setId(1);
        user.setName("aa");
        user.setAge(20);
        user.setBirthday("2011-2-22");
        user.setCar(null);
        user.setHave(true);
        user.setMajor(new String[]{"aa","bb"});
        user.setTime(new Date());
Gson gson=new Gson();
    
System.out.println(gson.toJson(user));
}

2.优点

public class User {
    private int id;
    @SerializedName("Name")
    private String name;
    private transient int age;
    private String birthday;
    private String[] major;
    private Object car;
    private boolean have;
    private Date time;

    public int getId() {
        return id;
    }

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

    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 getBirthday() {
        return birthday;
    }

    public void setBirthday(String birthday) {
        this.birthday = birthday;
    }

    public String[] getMajor() {
        return major;
    }

    public void setMajor(String[] major) {
        this.major = major;
    }

    public Object getCar() {
        return car;
    }

    public void setCar(Object car) {
        this.car = car;
    }

    public boolean isHave() {
        return have;
    }

    public Date getTime() {
        return time;
    }

    public void setTime(Date time) {
        this.time = time;
    }

    public void setHave(boolean have) {
        this.have = have;
    }


    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", name=‘" + name + ‘\‘‘ +
                ", age=" + age +
                ", birthday=‘" + birthday + ‘\‘‘ +
                ", major=" + Arrays.toString(major) +
                ", car=" + car +
                ", have=" + have +
                ‘}‘;
    }
}

[email protected]("Name") 加在属性上,可以修改属性在gson数据中的格式

2.使用transient关键字时,
private transient int age; 生成json数据时会忽略掉这个属性

3.可以格式化数据。
GsonBuilder gsonBuilder=new GsonBuilder();
gsonBuilder.setPrettyPrinting(); 输出的json数据更美观。
gsonBuilder.setDateFormat("yyyy-mm-dd");   提供日期转换,json只能提供string格式的日期
Gson gson=gsonBuilder.create();

三.自定义返回的Json数据格式

import com.fasterxml.jackson.annotation.JsonInclude;

import java.io.Serializable;

/**
 * ajax 请求的返回类型封装JSON结果
 */
@JsonInclude(JsonInclude.Include.NON_NULL)
public class BaseResult<T> implements Serializable {


    private static final long serialVersionUID = -4185151304730685014L;

    private boolean success;

    private T data;

    private String error;

    public BaseResult(boolean success, String error) {
        this.success = success;
        this.error = error;
    }

    public BaseResult(boolean success, T data) {
        this.success = success;
        this.data = data;
    }

    public boolean isSuccess() {
        return success;
    }

    public void setSuccess(boolean success) {
        this.success = success;
    }

    public T getData() {
        return data;
    }

    public void setData(T data) {
        this.data = data;
    }

    public String getError() {
        return error;
    }

    public void setError(String error) {
        this.error = error;
    }

    @Override
    public String toString() {
        return "BaseResult [success=" + success + ", data=" + data + ", error=" + error + "]";
    }

}

 

 
 
 

 












以上是关于Json的主要内容,如果未能解决你的问题,请参考以下文章

json 可视代码工作室Angular with Firebase片段

vs code 用户代码片段 html.json

错误代码:错误域 = NSCocoaErrorDomain 代码 = 3840“JSON 文本没有以数组或对象和允许未设置片段的选项开头。”

如何在android中将json数据加载到片段中

使用 json rereiver php mysql 在片段中填充列表视图

VS Code配置markdown代码片段