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

  • 43
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值