英文:
Build JSON string from String and Map<String, String> fields with GSon?
问题
以下是翻译好的部分:
我正在尝试围绕JSON编写一个用于发送WebSocket消息的包装器。我创建了这个类,允许您使用事件名称构造,然后传递一个关联数组的事件数据。
在 getString
方法中如何解析JSON,就像这样,这里是JSON的示例:
{
"event_name": "some event name",
"event_data": {
"some data": "some data value",
"some more data": "some more data value"
}
}
类:
package com.eu.websockets.events.server;
import java.util.HashMap;
import java.util.Map;
public abstract class ServerWebSocketEvent {
private String eventName;
private Map<String, String> eventData;
public ServerWebSocketEvent(String eventName) {
this.eventName = eventName;
this.eventData = new HashMap<>();
}
public void addEventData(String key, String value) {
eventData.put(key, value);
}
public String getString() {
}
}
英文:
I am trying to write a wrapper around JSON for sending websocket messages. I've created this class which allows you to construct with an event name, and then pass an associative array of event data.
How can I parse JSON in the getString
method like this, here is an example of the JSON:
{
"event_name": "some event name",
"event_data": {
"some data": "some data value",
"some more dat": "some more data value"
}
}
Class:
package com.eu.websockets.events.server;
import java.util.HashMap;
import java.util.Map;
public abstract class ServerWebSocketEvent {
private String eventName;
private Map<String, String> eventData;
public ServerWebSocketEvent(String eventName) {
this.eventName = eventName;
this.eventData = new HashMap<>();
}
public void addEventData(String key, String value) {
eventData.put(key, value);
}
public String getString() {
}
}
答案1
得分: 1
要使字段名称与您提供的 JSON 中不同,您需要使用 @SerializedName
进行指示,或者在这种情况下,您还可以将 FieldNamingPolicy
设置为您的 Gson
。
使用 @SerializedName
:
@SerializedName("event_name")
private String eventName;
@SerializedName("event_data")
private Map<String, String> eventData;
...
public String getString() {
return new Gson().toJson(this);
}
或者使用类似于以下方式的 FieldNamingPolicy
:
public String getString() {
return new GsonBuilder()
.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES)
.setPrettyPrinting() // 如果需要的话可以使用,以保持格式
.create()
.toJson(this);
}
英文:
To have field names different as in the JSON you present you need either to instruct that with @SerializedName
or in this case you can also set FieldNamingPolicy
to your Gson
.
So with @SerializedName
:
@SerializedName("event_name")
private String eventName;
@SerializedName("event_data")
private Map<String, String> eventData;
...
public String getString() {
return new Gson().toJson(this)
}
or with FieldNamingPolicy
like:
public String getString()
return new GsonBuilder()
.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES)
.setPrettyPrinting() // This one is not needed use if you want to
.create().toJson(this);
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论