gpt4 book ai didi

java - 如何将java对象序列化为field.path = field.value

转载 作者:太空宇宙 更新时间:2023-11-04 13:27:06 24 4
gpt4 key购买 nike

我有以下模型类:

package com.ab.model;

import java.util.List;

public class Request {

public Request(String requestType, Body body, List<String> emails) {
this.requestType = requestType;
this.body =body;
this.emails = emails;
}

private String requestType;
private Body body;
private List<String> emails;

public String getRequestType() {
return requestType;
}

public void setRequestType(String requestType) {
this.requestType = requestType;
}

public Body getBody() {
return body;
}

public void setBody(Body body) {
this.body = body;
}

public List<String> getEmails() {
return emails;
}

public void setEmails(List<String> emails) {
this.emails = emails;
}

}

class Body {

private String content;
private List<Header> headers;

public Body(String content, List<Header> headers) {
this.content = content;
this.headers = headers;
}

public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public List<Header> getHeaders() {
return headers;
}
public void setHeaders(List<Header> headers) {
this.headers = headers;
}

}

class Header {

private String headerName;

public Header (String headerName) {
this.headerName = headerName;
}

public String getHeaderName() {
return headerName;
}

public void setHeaderName(String headerName) {
this.headerName = headerName;
}

}

以及 Request 类的以下实例:

Request request = new Request(
"get",
new Body("abcdefg",
Arrays.asList(new Header("header_one"))),
Arrays.asList("a@a.com", "b@b.com"));

你知道有什么库或算法可以将请求对象序列化为以下字符串吗?

requestType = "get"
body.content = "abcdefg"
body.headers[0].headerName = "header_one"
emails[0] = "a@a.com"
emails[1] = "b@b.com"

我知道我可以将其序列化为 json、xml 等,但这些不适合我的用例。基本上我需要一个序列化,例如:field.nestedField.reallyNestedField = "其原始值"

下一步,我计划读取生成的字符串并为每个字段/nestedField 生成任意数据,然后使用 Apache 的 PropertyUtils 将其反序列化,例如:

PropertyUtils.setProperty(requestObject, "requestType", "random type");
PropertyUtils.setProperty(requestObject, "body.content", "random content");
//...

非常感谢!安德烈

最佳答案

重写toString()默认方法来读取成员变量并将其输出为文本怎么样?您可以使用 super 来引用您的 SuperClass 及其成员。

PS:您的类中没有默认构造函数!如果您的构造函数带有参数列表,建议您在类中包含无参数默认构造函数!特别是如果您正在实现一些与序列化/反序列化相关的逻辑!

关于java - 如何将java对象序列化为field.path = field.value,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32537683/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com