How to serialise a POJO to be sent over a Java RSocket?(如何序列化通过Java RSocket发送的POJO?)
问题描述
我正在尝试通过RSocket请求流发送POJO:
import java.io.Serializable;
class GreetingRequest implements Serializable {
private String name;
public GreetingRequest() {}
public GreetingRequest(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
如果我要发送字符串,我可以这样做:
ByteBuf data = ByteBufAllocator.DEFAULT.buffer().writeBytes("Hello".getBytes());
socket.requestStream(DefaultPayload.create(data, metadata))
.map(Payload::getDataUtf8)
.toIterable()
.forEach(System.out::println);
但是我如何将我的POJO序列化?
这是我尝试使用不起作用的implementation group: 'org.apache.commons', name: 'commons-lang3', version: '3.12.0'
:
GreetingRequest pojo = new GreetingRequest("Davide");
ByteBuf data = SerializationUtils.serialize(pojo);
socket.requestStream(DefaultPayload.create(data, metadata))
.map(Payload::getDataUtf8)
.toIterable()
.forEach(System.out::println);
推荐答案
我建议您使用GSON转换器。它可以帮助您将Java类转换为JSON字符串。然后您可以像处理简单文本一样使用字符串。
您可以导入依赖项:
dependencies {
implementation 'com.google.code.gson:gson:2.8.7'
}
然后,可以使用jsonschema2pojo将JSON:
{ "name": "Test" }
添加到类似This:
的类 package com.example;
import javax.annotation.Generated;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class GreetingRequest {
@SerializedName("name")
@Expose
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
完成所有操作后,您可以在Java中执行以下操作:
Gson converter = new Gson();
GreetingsRequest request = new GreetingRequest();
request.setName("Test");
String greetingsJSON = converter.toJson(request);
然后您仍然可以按如下方式发送JSON字符串:
ByteBuf data = ByteBufAllocator.DEFAULT.buffer().writeBytes(greetingsJSON.getBytes());
socket.requestStream(DefaultPayload.create(data, metadata))
.map(Payload::getDataUtf8)
.toIterable()
.forEach(System.out::println);
数据转换:
- JSON对象-Java类
- 数组列表
帮助链接:
这是您需要在Java中包含(包含教程)的库:GSON Converter Git
这是一个JSON到Class Online转换器:Jsonschema2pojo generator
这篇关于如何序列化通过Java RSocket发送的POJO?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何序列化通过Java RSocket发送的POJO?


- 未找到/usr/local/lib 中的库 2022-01-01
- 在 Java 中,如何将 String 转换为 char 或将 char 转换 2022-01-01
- java.lang.IllegalStateException:Bean 名称“类别"的 BindingResult 和普通目标对象都不能用作请求属性 2022-01-01
- 转换 ldap 日期 2022-01-01
- 如何使 JFrame 背景和 JPanel 透明且仅显示图像 2022-01-01
- 将 Java Swing 桌面应用程序国际化的最佳实践是什么? 2022-01-01
- Eclipse 的最佳 XML 编辑器 2022-01-01
- GC_FOR_ALLOC 是否更“严重"?在调查内存使用情况时? 2022-01-01
- 获取数字的最后一位 2022-01-01
- 如何指定 CORS 的响应标头? 2022-01-01