Map和List输入的两种不同json格式

一、List to json格式

复制代码
[{"@type":"top.lovemom.pojo.ESP8266","devicePosition":"家里的阳台","deviceRemark":"我的设备1","publicIp":"127.0.0.1","userEmail":"123b@ggb.top"},{"@type":"top.lovemom.pojo.HardwareLED","stateCurrentLED":1,"statusControlLED":0,"timeCurrentLED":"2024-03-31 15:48:53"}]

1.1 list解析呈现

1.2 list json 生成 源码

复制代码
package top.lovemom.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;

import top.lovemom.pojo.ESP8266;
import top.lovemom.pojo.HardwareLED;

/**
 * Servlet implementation class TestServlet
 */
@WebServlet("/BW29y82UI")
public class GetContextServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public GetContextServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		String ip = request.getRemoteAddr();
		System.out.println("------------"+ip+"------------实现get请求");
		
		ESP8266 esp = new ESP8266();
		esp.setPublicIp(ip);
		esp.setUserEmail("123b@ggb.top");
		esp.setDeviceRemark("我的设备1");
		esp.setDevicePosition("家里的阳台");
		
		Date now = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String formattedDate = sdf.format(now);	
		
		HardwareLED led = new HardwareLED();
		led.setStateCurrentLED(1);
		led.setTimeCurrentLED(formattedDate);
		
		// 创建一个 List 对象来存储 ESP8266 和 HardwareLED 对象
		List<Object> objectList = new ArrayList<>();
		// 将 ESP8266 和 HardwareLED 对象添加到 List 中
        objectList.add(esp);
        objectList.add(led);
		
        // 将 List 对象转换为 JSON 字符串
        String respondJson = JSON.toJSONString(objectList, SerializerFeature.WriteClassName);
		
		// 设置响应的内容类型为application/json
	    response.setContentType("application/json");
	    response.setCharacterEncoding("UTF-8");
	    // 获取响应的输出流
	    PrintWriter out = response.getWriter();
	    // 将JSON字符串写回客户端
	    out.println(respondJson);
	    out.flush();
		
	}

}

二、Map to json格式

复制代码
{"top.lovemom.pojo.ESP8266":{"devicePosition":"家里的阳台","deviceRemark":"我的设备1","publicIp":"127.0.0.1","userEmail":"123b@ggb.top"},"top.lovemom.pojo.HardwareLED":{"stateCurrentLED":1,"statusControlLED":0,"timeCurrentLED":"2024-03-31 15:58:50"}}

2.1 map解析呈现

2.2 map json 生成 源码

复制代码
package top.lovemom.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSON;

import top.lovemom.pojo.ESP8266;
import top.lovemom.pojo.HardwareLED;

@WebServlet("/BW29y82UI")
public class GetContextServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    public GetContextServlet() {
        super();
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        String ip = request.getRemoteAddr();
        System.out.println("------------" + ip + "------------实现get请求");

        ESP8266 esp = new ESP8266();
        esp.setPublicIp(ip);
        esp.setUserEmail("123b@ggb.top");
        esp.setDeviceRemark("我的设备1");
        esp.setDevicePosition("家里的阳台");

        Date now = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String formattedDate = sdf.format(now);

        HardwareLED led = new HardwareLED();
        led.setStateCurrentLED(1);
        led.setTimeCurrentLED(formattedDate);

        // 创建一个 Map 对象来存储 ESP8266 和 HardwareLED 对象
        Map<String, Object> jsonObject = new LinkedHashMap<>();
        // 将 ESP8266 和 HardwareLED 对象添加到 Map 中
        jsonObject.put(esp.getClass().getName(), esp);
        jsonObject.put(led.getClass().getName(), led);

        // 将 Map 对象转换为 JSON 字符串
        String respondJson = JSON.toJSONString(jsonObject);

        // 设置响应的内容类型为application/json
        response.setContentType("application/json");
        response.setCharacterEncoding("UTF-8");
        // 获取响应的输出流
        PrintWriter out = response.getWriter();
        // 将JSON字符串写回客户端
        out.println(respondJson);
        out.flush();
    }
}

三、说明

在Java中,List和Map是两种不同的数据结构,它们在生成JSON格式数据时可以产生不同的输出。

  1. List生成JSON格式

    • 当使用List存储对象时,通常会将对象按顺序存储在List中。在将List转换为JSON格式时,对象的顺序会被保留,JSON数组中的元素顺序与List中的顺序一致。这意味着在前端处理JSON数据时,可以根据元素在数组中的位置来访问和操作数据。
    • 例如,在你的代码中,你将ESP8266和HardwareLED对象存储在List中,然后将List转换为JSON格式,输出的JSON数组中的元素顺序与List中的顺序一致。
  2. Map生成JSON格式

    • 使用Map时,可以使用键值对的方式存储数据。在将Map转换为JSON格式时,键值对会被转换为JSON对象的属性和值。键值对在JSON对象中没有固定的顺序,它们的顺序不影响JSON对象的解析和处理。
    • 例如,在修改后的代码中,你创建了一个Map对象来存储ESP8266和HardwareLED对象,然后将Map转换为JSON格式,输出的JSON对象中的属性顺序不受影响,因为JSON对象中的属性顺序在规范中并不重要。

通常情况下属性用List、对象用Map

JSON格式对前后端分离的重要性

JSON格式在前后端分离架构中扮演了重要角色,具有以下几个方面的重要性:

  1. 数据交换标准:JSON作为一种轻量级的数据交换格式,被广泛应用于前后端数据传输中。前端通过HTTP请求从后端获取JSON格式的数据,然后可以使用JavaScript轻松地解析和处理这些数据。

  2. 灵活性和可读性:JSON具有简洁清晰的结构,易于阅读和理解。它支持复杂的数据结构,包括嵌套对象和数组,使得可以传输各种类型的数据。

  3. 跨语言支持:JSON是一种语言无关的数据格式,几乎所有编程语言都有对JSON的解析和生成支持。这意味着可以在不同的技术栈之间轻松地传递数据,实现跨平台的数据交换。

  4. 前后端分离:JSON格式的广泛应用促进了前后端分离架构的发展。通过将数据和界面逻辑分离,前端工程师可以专注于前端界面的开发和优化,而后端工程师则可以专注于数据处理和业务逻辑的实现。这种分离提高了开发效率和代码的可维护性。

因此,JSON格式在前后端分离架构中扮演了至关重要的角色,它提供了一种简单、灵活、跨平台的数据交换方式,促进了前后端的协作和开发效率。

相关推荐
吳所畏惧5 小时前
少走弯路:uniapp里将h5链接打包为apk,并设置顶/底部安全区域自动填充显示,阻止webview默认全屏化
android·安全·uni-app·json·html5·webview·js
咖丨喱7 小时前
【对端发送的invitation req中channel list和operating channel的operating class不对应】
数据结构·list·asp.net
骇客野人8 小时前
JAVA获取一个LIST中的最大值
java·linux·list
CaliXz9 小时前
取出51.la统计表格内容为json数据 api
java·javascript·json
songgz10 小时前
多线程双向 JSON 解析器
java·服务器·json
xcLeigh10 小时前
超全 Kingbase KES V9R3C15 JSON 函数指南:从基础操作到高级应用
json·函数·国产数据库·kingbase·金仓数据库
曹牧10 小时前
Java:list<map<string,sting>>与C#互操作
java·c#·list
差点GDP19 小时前
模拟请求测试 Fake Rest API Test
前端·网络·json
ID_1800790547320 小时前
基于 Python 的 Cdiscount 商品详情 API 调用与 JSON 核心字段解析(含多规格 SKU 提取)
开发语言·python·json
闲人编程20 小时前
OpenAPI/Swagger规范与API文档自动化
运维·自动化·json·swagger·schema·openapi·codecapsule