JavaScript Object Notation

本文介绍了JSON格式,其键值对和数组结构,以及在Java中如何通过Fastjson进行数据转换。展示了JSON.parseObject和toJSONString的使用示例,以及解析JSON字符串的各种方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、简述

因为 xml 整合到 html 中各个浏览器实现的细节不尽相同,所以从 JS 的数据类型中提取了一个子集,作为新的数据交换格式,因为主流的浏览器使用了通用的 JavaScript 引擎组件,所以在解析这种新数据格式时就不存在兼容性问题,于是将这种数据格式命名为 “JavaScript Object Notation”,缩写为 JSON。

二、JSON 格式

1️⃣键值对形式

{
 "person": {
     "name": "wg",
     "age": "18",
     "sex": "female",
     "hometown": {
         "province": "浙江省",
         "city": "杭州市"
      }
   }
}

这种结构的 JSON 数据规则是:一个无序的“名称/值”对集合,一个对象以{左括号开始,}右括号结束。每个“名称”后跟一个:冒号;“名称/值”对之间使用,逗号分隔。

2️⃣数组形式

["xp", 18, "female", "浙江省杭州市"]

数组形式的 JSON 数据就是值(value)的有序集合。一个数组以[左中括号开始,]右中括号结束。值之间使用,逗号分隔。

三、JOSN 的六种数据类型

JSON 内部都是包含 value 的,那 JSON 的 value 到底有哪些类型?

1️⃣String:字符串,必须要用双引号引起来。
2️⃣number:数值,与 JavaScript 的 number 一致,整数(不使用小数点或指数计数法)最多为 15 位。小数的最大位数是 17。
3️⃣object:JavaScript 的对象形式,{key:value}表示方式,可嵌套。
4️⃣array:数组,JavaScript 的 Array 表示方式[value ],可嵌套。
5️⃣true/false:布尔类型,JavaScript 的 boolean 类型。
6️⃣null:空值,JavaScript 的 null。

四、应用示例

JSON.parseObject,是将 Json 字符串转化为相应的对象。JSON.toJSONString 则是将对象转化为 Json 字符串。

首先用 maven 引入 fastjson

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
 
    <groupId>com.wujiang.test</groupId>
    <artifactId>test</artifactId>
    <version>1.0-SNAPSHOT</version>
 
    <properties>
        <fastjson_version>1.2.28</fastjson_version>
    </properties>
 
    <dependencies>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>${fastjson_version}</version>
        </dependency>
    </dependencies>
</project>

定义一个 model 类,如下所示:

@Data
public class Staff {
    private String name;
    private Integer age;
    private String sex;
    private Date birthday;
}

测试:

import com.alibaba.fastjson.JSON;

public class jsonTest {
    public static void main(String[] args) {
        // json字符串转化为对象
        String jsonString = "{name:'xp',age:18,sex:'female',telephone:'88888'}";
        Staff staff = JSON.parseObject(jsonString, Staff.class);
        System.out.println(staff.toString());
 
        // 对象转化为json字符串
        String jsonStr = JSON.toJSONString(staff);
        System.out.println(jsonStr);
    }
}

输出结果:

Staff{name='xp', age=18, sex='female', birthday=null}

{"age":18,"name":"xp","sex":"female"}

在 JSON.parseObject 的时候,会去填充名称相同的属性。对于 Json 字符串中没有,而 model 类有的属性,会为 null;对于 model 类没有,而 Json 字符串有的属性,不做任何处理。

五、test

import java.text.ParseException;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import java.util.Map;


public class Testmain {
    public static void main(String[] args) throws ParseException {

        String str = "{abcdefgConfig:['123,aaa,wg;','456,bbb,xxp']}";
        System.out.println(str);

        //第一种方式
        Map maps = (Map) JSON.parse(str);
        System.out.println("---1.用JSON类来解析JSON字符串---");
        for (Object map : maps.entrySet()) {
            System.out.println(((Map.Entry) map).getKey() + "  " + ((Map.Entry) map).getValue());
        }
        //第二种方式
        Map mapTypes = JSON.parseObject(str);
        System.out.println("---2.用JSON类的parseObject来解析JSON字符串---");
        for (Object obj : mapTypes.keySet()) {
            System.out.println("key为:" + obj + "值为:" + mapTypes.get(obj));
        }
        //第三种方式
        Map mapType = JSON.parseObject(str, Map.class);
        System.out.println("---3.用JSON类,指定解析类型,来解析JSON字符串---");
        for (Object obj : mapType.keySet()) {
            System.out.println("key为:" + obj + "值为:" + mapType.get(obj));
        }
        //第四种方式:JSONObject是Map接口的一个实现类
        Map json = (Map) JSONObject.parse(str);
        System.out.println("---4.用JSONObject类的parse方法来解析JSON字符串---");
        for (Object map : json.entrySet()) {
            System.out.println(((Map.Entry) map).getKey() + "  " + ((Map.Entry) map).getValue());
        }
        //第五种方式:JSONObject是Map接口的一个实现类
        JSONObject jsonObject = JSONObject.parseObject(str);
        System.out.println("---5.用JSONObject的parseObject方法来解析JSON字符串---");
        for (Object map : jsonObject.entrySet()) {
            System.out.println(((Map.Entry) map).getKey() + "  " + ((Map.Entry) map).getValue());
        }
        //第六种方式:JSONObject是Map接口的一个实现类
        Map mapObj = JSONObject.parseObject(str, Map.class);
        System.out.println("---6.用JSONObject的parseObject方法并执行返回类型来解析JSON字符串---");
        for (Object map : mapObj.entrySet()) {
            System.out.println(((Map.Entry) map).getKey() + "  " + ((Map.Entry) map).getValue());
        }
    }
}

结果:

{abcdefgConfig:['123,aaa,wg;','456,bbb,xxp']}
---1.用JSON类来解析JSON字符串---
abcdefgConfig  ["123,aaa,wg;","456,bbb,xxp"]
---2.用JSON类的parseObject来解析JSON字符串---
key为:abcdefgConfig值为:["123,aaa,wg;","456,bbb,xxp"]
---3.用JSON类,指定解析类型,来解析JSON字符串---
key为:abcdefgConfig值为:["123,aaa,wg;","456,bbb,xxp"]
---4.JSONObject类的parse方法来解析JSON字符串---
abcdefgConfig  ["123,aaa,wg;","456,bbb,xxp"]
---5.JSONObject的parseObject方法来解析JSON字符串---
abcdefgConfig  ["123,aaa,wg;","456,bbb,xxp"]
---6.JSONObject的parseObject方法并执行返回类型来解析JSON字符串---
abcdefgConfig  ["123,aaa,wg;","456,bbb,xxp"]
### Object Notation in Programming and Data Exchange In programming and data exchange, object notation refers to a way of representing structured data using key-value pairs or collections. One widely adopted form is **JavaScript Object Notation (JSON)**, which serves as an open standard format that uses human-readable text to transmit data objects consisting of attribute–value pairs and array data types[^1]. JSON's simplicity and ease of use have made it particularly well-suited for web applications. A typical JSON structure looks like this: ```json { "name": "John Doe", "age": 30, "isEmployed": true, "address": { "street": "123 Main St", "city": "Anytown" }, "phoneNumbers": [ "+1-800-123-4567", "+1-800-987-6543" ] } ``` This example demonstrates how JSON can represent complex structures with nested objects and arrays while maintaining readability and compatibility across different platforms. For effective handling of such notations within programs written in languages like Go, developers often utilize libraries provided by the language itself. For instance, when working with I/O operations involving writers implementing `io.Writer` interfaces, one might employ functions from the `fmt` package alongside predefined variables such as `os.Stdout` and `os.Stderr`[^2]. When dealing with sensitive information represented through object notation formats including JSON, ensuring confidentiality becomes crucial. Variables containing personal identifiers or other private details must be handled securely throughout their lifecycle within software systems[^3]. --related questions-- 1. How does JSON compare against XML regarding performance and usability? 2. What are some common pitfalls encountered during serialization/deserialization processes involving JSON? 3. Can you provide examples demonstrating secure practices for managing confidential variables stored in JSON documents? 4. In what scenarios would someone prefer YAML over JSON for configuration files? 5. Are there specific considerations needed when validating user input received via REST APIs expecting JSON payloads?
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

JFS_Study

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值