首页 > 编程语言 > 详细

JAVA与JSON解析

时间:2021-05-17 13:39:58      阅读:13      评论:0      收藏:0      [点我收藏+]

什么是JSON?
?JSON 指的是 JavaScript 对象表示法(JavaScript Object Notation)
?JSON 是轻量级的文本数据交换格式
?JSON 独立于语言:JSON 使用 Javascript语法来描述数据对象,但是 JSON 仍然独立于语言和平台。JSON 解析器和 JSON 库支持许多不同的编程语言。 目前非常多的动态(PHP,JSP,.NET)编程语言都支持JSON。
?JSON 具有自我描述性,更易理解
为什么使用JSON?
对于 AJAX 应用程序来说,JSON 比 XML 更快更易使用:
使用 XML
?读取 XML 文档
?使用 XML DOM 来循环遍历文档
?读取值并存储在变量中
使用 JSON
?读取 JSON 字符串
?用 eval() 处理 JSON 字符串

Json语法
JSON 语法是 JavaScript 对象表示语法的子集。
?数据在名称/值对中
?数据由逗号分隔
?大括号{}保存对象
?中括号[]保存数组,数组可以包含多个对象
以谷歌的jar包为例说明;
JSON文件的下载--Gson。
Gson
将对象转换为JSON字符串
转换JSON字符串的步骤:

  1. 引入JAR包
  2. 在需要转换JSON字符串的位置编写如下代码即可:
    String json = new Gson().toJSON(要转换的对象);
    案例:
    Book b = BookDao.find();
    String json = new Gson().toJson(b);
    System.out.println(json);

将JSON字符串转换为对象

  1. 引入JAR包
  2. 在需要转换Java对象的位置, 编写如下代码:
    对象 = new Gson().fromJson(JSON字符串,对象类型.class);
    案例:
    String json = "{"id":1,"name":"海贼王","author":"忘记了
    ","info":"嘿嘿嘿嘿嘿嘿","price":198.0}";
    Book book = new Gson().fromJson(json, Book.class);
    System.out.println(book);

`package com.java.ywl.Google;

import com.google.gson.Gson;

public class Demo1 {
public static void main(String[] args) {
//利用谷歌的jar包转换,将对象转换为JSON格式的字符串
//1.常见Gson对象
Gson g = new Gson();
//2.转换
Student s = new Student("100","路飞","海贼王");
String a = g.toJson(s);
System.out.println(a);

}

}`

`package com.java.ywl.Google;

import java.util.Objects;

public class Student {

public String id;
public String name;
public String info;
@Override
public String toString() {
    return "Student{" +
            "id=‘" + id + ‘\‘‘ +
            ", name=‘" + name + ‘\‘‘ +
            ", info=‘" + info + ‘\‘‘ +
            ‘}‘;
}

public Student() {
}

public Student(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;
}

@Override
public boolean equals(Object o) {
    if (this == o) return true;
    if (o == null || getClass() != o.getClass()) return false;
    Student student = (Student) o;
    return Objects.equals(id, student.id) && Objects.equals(name, student.name) && Objects.equals(info, student.info);
}

@Override
public int hashCode() {
    return Objects.hash(id, name, info);
}

}
`

JAVA与JSON解析

原文:https://www.cnblogs.com/Y516681464/p/14776176.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!