java json注册_做java这么久了居然还不知道JSON的使用(一文带你了解)

JSON(JavaScript Object Notation, NS对象标记)是一种轻量级的数据交换格式,目前使用特别广泛。

采用完全独立于编程语言的 文本格式 来存储和表示数据。

简洁和清晰的层次结构使得JSON成为理想的数据交换语言。

易于人阅读和编写,同时也易于机器解析和生成,并有效地提升网络传输效率。

在JavaScript语言中,一切都是对象。因此,任何JavaScript 支持的类型都可以通过JSON来表示,例如字符串、数字、对象、数组等。看看他的要求和语法格式:

对象表示为键值对,数据由逗号分隔

花括号保存对象

方括号保存数组

JSON键值对是用来保存JavaScript对象的一种方式,和JavaScript对象的写法也大同小异,键/值对组合中的键名写在前面并用双引号 “” 包裹,使用冒号 : 分隔,然后紧接着值:

{"name":"zhangsan"}

{"age":"3"}

{"sex":"男"}

JSON是JavaScript对象的字符串表示法,它使用文本表示一个JS对象的信息,本质是一个字符串。

var obj = {a:'Hello',b:'World'};//这是一个对象,注意键名也是可以使用引号包裹的

var json = '{a:"Hello",b:"World"}';//这是一个JSON字符串,本质是一个字符串

JSON和 JavaScript 对象互转

要实现从JSON字符串转换为JavaScript对象,使用JSON.parse()方法:

var obj = JSON.parse('{a:"Hello",b:"World"}');

//结果是 {a:'Hello',b:'World'}

要实现从JavaScript对象转化为JSON字符串,使用JSON.stringify()方法:

var json = JSON.stringify({a:'Hello',b:'World'});

//结果是 '{a:"Hello",b:"World"}'

代码测试

新建一个module,spring-05-json,添加web支持 在web目录下新建一个jsontest.html,编写测试内容

Title

//编写一个JavaScript对象

var user={

name:"张三",

age:3,

sex:"男"

};

console.log(user);

//将 js 对象转换为 json 对象;

var json = JSON.stringify(user);

console.log(json);

//将 json 对象转换为 js 对象;

var obj = JSON.parse(json);

console.log(obj);

在IDEA中使用浏览器打开,查看控制台输出。

d29836c2df71ddcd4cc61376c2647b43.png

Controller返回 JSON数据

Jackson应该是目前比较好的json解析工具了

当然工具不止这一个,比如还有阿里巴巴的 fastjson 等等。

我们这里使用 Jackson,使用它需要导入它的jar包。

Jackson

com.fasterxml.jackson.core

jackson-databind

2.9.9

配置SpringMVC需要的配置文件

web.xml

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"

version="4.0">

SpringMVC

org.springframework.web.servlet.DispatcherServlet

contextConfigLocation

classpath:springmvc-servlet.xml

1

SpringMVC

/

encoding

org.springframework.web.filter.CharacterEncodingFilter

encoding

utf-8

encoding

/*

springmvc.xml

xmlns:mvc="http://www.springframework.org/schema/mvc"

xmlns:context="http://www.springframework.org/schema/context"

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

xsi:schemaLocation=" http://www.springframework.org/schema/beans

http://www.springframework.org/schema/beans/spring-beans.xsd

http://www.springframework.org/schema/mvc

http://www.springframework.org/schema/mvc/spring-mvc.xsd

http://www.springframework.org/schema/context

http://www.springframework.org/schema/context/spring-context.xsd">

编写一个User实体类

//需要导入lombok

@Data

@AllArgsConstructor

@NoArgsConstructor

public class User {

private String name;

private int age;

private String sex;

}

编写一个测试类Controller

@Controller

public class UserController {

@RequestMapping("/json1")

@ResponseBody //他就不去走视图解析器,直接返回一个字符串

public String json1() throws Exception{

//jackson

ObjectMapper mapper =new ObjectMapper();

User user = new User("张三01",21,"男");

String str = mapper.writeValueAsString(user);

return str;

}

}

配置Tomcat , 启动测试一下!

http://localhost:8080/json1

83bd4dfa67752c13fa916a8a449ceba2.png

发现出现了乱码问题,我们需要设置一下他的编码格式为utf-8,以及它返回的类型;

通过@RequestMapping的produces属性来实现,修改下代码:

//没有在配置文件中配置,可以单个解决乱码

//produces:指定响应体返回类型和编码

@RequestMapping(value = "/json1",produces = "application/json;charset=utf-8")

再次测试, http://localhost:8080/json1 , 乱码问题OK!

cd615b0f53d908435baf4ad23a6e549e.png

乱码统一解决

上一种方法比较麻烦,如果项目中有许多请求则每一个都要添加,可以通过Spring配置统一指定,这样就不用每次都去处理了!

我们可以在springmvc的配置文件上添加一段消息StringHttpMessageConverter转换配置!

返回json字符串统一解决

在类上直接使用 @RestController ,这样子,里面所有的方法都只会返回 json 字符串了,不用再每一个都添加@ResponseBody !我们在前后端分离开发中,一般都使用 @RestController ,十分便捷!

@RestController

public class UserController {

//produces:指定响应体返回类型和编码

@RequestMapping(value = "/json1")

public String json1() throws JsonProcessingException {

//创建一个jackson的对象映射器,用来解析数据

ObjectMapper mapper = new ObjectMapper();

//创建一个对象

User user = new User("张三1号", 3, "男");

//将我们的对象解析成为json格式

String str = mapper.writeValueAsString(user);

//由于@ResponseBody注解,这里会将str转成json格式返回;十分方便

return str;

}

}

启动tomcat测试,结果都正常输出!

测试集合输出

增加一个新的方法

@RequestMapping("/json2")

@ResponseBody //他就不去走视图解析器,直接返回一个字符串

public String json2() throws Exception{

//jackson

ObjectMapper mapper =new ObjectMapper();

List userList = new ArrayList();

User user1 = new User("张三01",21,"男");

User user2 = new User("张三02",21,"男");

User user3 = new User("张三03",21,"男");

User user4 = new User("张三04",21,"男");

userList.add(user1);

userList.add(user2);

userList.add(user3);

userList.add(user4);

String str = mapper.writeValueAsString(userList);

return str;

}

运行结果 : 没有任何问题!

6afcdf06458f2396a5af7b70a2229b1a.png

输出时间对象

增加一个新的方法

@RequestMapping("/json3")

public String json3() throws JsonProcessingException {

ObjectMapper mapper = new ObjectMapper();

//创建时间一个对象,java.util.Date

Date date = new Date();

//将我们的对象解析成为json格式

String str = mapper.writeValueAsString(date);

return str;

}

运行结果 :

8f0af90eeb42df562bb764750b7681c9.png

默认日期格式会变成一个数字,是1970年1月1日到当前日期的毫秒数!

Jackson 默认是会把时间转成timestamps形式

解决方案一:使用SimpleDateFormat,自定义时间格式

@RequestMapping("/json3")

@ResponseBody //他就不去走视图解析器,直接返回一个字符串

public String json3() throws Exception {

//jackson

ObjectMapper mapper = new ObjectMapper();

Date date = new Date();

//自定义日期格式

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

return mapper.writeValueAsString(sdf.format(date));

}

解决方案二:取消timestamps形式 , 自定义时间格式

@RequestMapping("/json4")

@ResponseBody //他就不去走视图解析器,直接返回一个字符串

public String json4() throws Exception {

//jackson

ObjectMapper mapper = new ObjectMapper();

//不使用时间戳的方式、

mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS,false);

//自定义日期格式

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

mapper.setDateFormat(sdf);

Date date = new Date();

return mapper.writeValueAsString(date);

}

运行结果 : 成功的输出了时间!

213cea531dca04e395868ecd272bd7df.png

抽取成工具类

如果要经常使用的话,这样是比较麻烦的,我们可以将这些代码封装到一个工具类中;我们去编写下

public class JSONUtils {

public static String getJson(Object object){

return getJson(object,"yyyy-MM-dd HH:mm:ss");

}

public static String getJson(Object object,String dateFormat){

//jackson

ObjectMapper mapper = new ObjectMapper();

//不使用时间戳的方式

mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS,false);

//自定义日期格式

SimpleDateFormat sdf = new SimpleDateFormat(dateFormat);

mapper.setDateFormat(sdf);

try {

return mapper.writeValueAsString(object);

} catch (JsonProcessingException e) {

e.printStackTrace();

}

return null;

}

}

此时的代码更加简洁。

@RequestMapping("/json5")

@ResponseBody //他就不去走视图解析器,直接返回一个字符串

public String json5() throws Exception {

Date date = new Date();

return JSONUtils.getJson(date,"yyyy-MM-dd HH:mm:ss");

}

FastJson

fastjson.jar是阿里开发的一款专门用于Java开发的包, 可以方便的实现json对象与JavaBean对象的转换,实现JavaBean对象与json字符串的转换,实现json对象 与json字符串的转换。实现json的转换方法很多,最后的实现结果都是一样的。

导入pom依赖

com.alibaba

fastjson

1.2.20

【JSONObject代表json对象】

JSONObject实现了Map接口,猜想JSONObject底层操作是由Map实现的。

JSONObject对应 json对象,通过各种形式的get()方法可以获取json对象中的数据,也可利用诸如size(),isEmpty()等方法获取"键: 值"对的个数和判断是否为空。其本质是通过实现Map接口并调用接口中的方法完成的。

【JSONArray代表json对象数组】

内部是有List接口中的方法来完成操作的。

【JSON代表JSONObject和 JSONArray的转化】

JSON类源码分析与使用。

仔细观察这些方法,主要是实现json对象,json对象数组,javabean对象,json字符串之间的相互转化。

代码测试:

@RequestMapping("/json6")

@ResponseBody

public String json6() throws Exception {

List userList = new ArrayList();

User user1 = new User("张三01",21,"男");

User user2 = new User("张三02",21,"男");

User user3 = new User("张三03",21,"男");

User user4 = new User("张三04",21,"男");

userList.add(user1);

userList.add(user2);

userList.add(user3);

userList.add(user4);

System.out.println("****Java对象 转 JSON字符串****");

String str1 = JSON.toJSONString(userList);

System.out.println(str1);

String str2 = JSON.toJSONString(user1);

System.out.println(str2);

System.out.println("****JSON字符串 转 Java对象****");

User jp_user1 = JSON.parseObject(str2, User.class);

System.out.println(jp_user1);

System.out.println("****Java对象 转 JSON对象****");

JSONObject jsonObject1 = (JSONObject) JSON.toJSON(user2);

System.out.println(jsonObject1.getString("name"));

System.out.println("****JSON对象 转 Java对象****");

User to_java_user = JSON.toJavaObject(jsonObject1, User.class);

System.out.println(to_java_user);

return "Hello";

}

到此这篇关于做java这么久了居然还不知道JSON的使用(一文带你了解)的文章就介绍到这了,更多相关java中json使用内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要将JSON文档数组插入MongoDB,可以使用MongoDB的Java驱动程序和BSON库来实现。 下面是一个简单的示例代码,演示如何将JSON文档数组插入MongoDB。 ```java import com.mongodb.MongoClient; import com.mongodb.client.MongoCollection; import com.mongodb.client.MongoDatabase; import org.bson.Document; import org.json.JSONArray; import org.json.JSONObject; public class InsertJsonArrayToMongoDB { public static void main(String[] args) { // 创建MongoDB客户端 MongoClient mongoClient = new MongoClient("localhost", 27017); // 获取要使用的数据库 MongoDatabase db = mongoClient.getDatabase("test"); // 获取要使用的集合 MongoCollection<Document> collection = db.getCollection("mycollection"); // 创建JSON文档数组 JSONArray jsonArray = new JSONArray(); JSONObject json1 = new JSONObject(); json1.put("name", "John"); json1.put("age", 30); jsonArray.put(json1); JSONObject json2 = new JSONObject(); json2.put("name", "Mary"); json2.put("age", 25); jsonArray.put(json2); // 将JSON文档数组转换为BSON文档数组 Document[] docs = new Document[jsonArray.length()]; for (int i = 0; i < jsonArray.length(); i++) { JSONObject json = jsonArray.getJSONObject(i); Document doc = Document.parse(json.toString()); docs[i] = doc; } // 将BSON文档数组插入MongoDB collection.insertMany(Arrays.asList(docs)); // 关闭MongoDB客户端 mongoClient.close(); } } ``` 需要注意的是,上述代码中将JSON文档数组转换为BSON文档数组时,使用了`Document.parse(json.toString())`方法。这是因为MongoDB的Java驱动程序不支持直接将JSONObject对象转换为BSON文档对象,需要先将JSONObject对象转换为JSON字符串,再使用`Document.parse()`方法将JSON字符串转换为BSON文档对象。 如果在插入JSON文档数组时出现错误,可以检查JSON文档的格式是否正确,以及转换为BSON文档时是否有误。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值