Netty中json编解码器(gson实现编码 fastjson实现解码)

谁说胖子不能爱 提交于 2020-04-26 17:36:35

1.ProtoMgr.java

package com.my.Game.Proto;

import com.alibaba.fastjson.JSON;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

public class ProtoMgr {
    static private GsonBuilder gb = new GsonBuilder();
    static private final Gson gson;

    static {
        gb.disableHtmlEscaping();
        gson = gb.create();
    }

    /**
     * json编码器
     *
     * @param ctype
     * @param body
     * @return
     */
    public static String jsonEncode(int ctype, Object body) {
        String json = gson.toJson(new Body(ctype, body));
        return json;
    }

    /**
     * json解码器
     *
     * @param json
     * @param tClass
     * @param <T>
     * @return
     */
    public static <T> T jsonDecode(String json, Class<T> tClass) {
        T t = JSON.parseObject(json, tClass);
        return t;
    }

    private static class Body {
        public int ctype;
        public Object body;

        public Body(int ctype, Object body) {
            this.ctype = ctype;
            this.body = body;
        }
    }
}

2.IOHandler.java

  @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, WebSocketFrame webSocketFrame) throws Exception {
        if (webSocketFrame instanceof TextWebSocketFrame) {
            String str = ((TextWebSocketFrame) webSocketFrame).text();
            logger.info(str);

            int ctype = 2;
            Object body = new TestResp();

            String strResp = ProtoMgr.jsonEncode(ctype, body);

            channelHandlerContext.channel().writeAndFlush(new TextWebSocketFrame(strResp));
        } else {
            String message = webSocketFrame.getClass().getName();
            logger.error("无法处理的类型{}", message);
        }
    }

复杂的数据类型

package com.my.Game.Proto;

import java.util.ArrayList;
import java.util.Arrays;


public class TestResp {
    public int age = 22;
    public ArrayList<Rank> rankList = new ArrayList<>(Arrays.asList(new Rank(), new Rank(), new Rank(), new Rank(), new Rank()));


    static private class Rank {
        public int rank = 1;
        public ArrayList<String> nameList = new ArrayList<>(Arrays.asList("jn", "xx", "cx"));
    }
}

 

 

 

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!