gpt4 book ai didi

java - 使用 GWT Overlay 类型将 JSON String 转换为 POJO

转载 作者:行者123 更新时间:2023-11-29 18:20:55 24 4
gpt4 key购买 nike

这是我需要转换为 POJO 以便在我的 GWT 应用程序中轻松访问的字符串:

{"title":"test","content":"test","id":1,"user":null,"hash":null,"created":1379569937945,"modified":1379569937945,"password":null,"views":0}

查看此答案:Parse json with gwt 2.0

Overlay 类型似乎很容易做到。但是那里的示例显示例如获取 ID:

    public final native int getId() /*-{
return parseInt(this.u[0]);
}-*/;

问题是我的 GWT 应用程序获取字段顺序的 JSON 字符串可能会改变。为此可以做什么?我不是 Javascript 专家,但这段代码显示获取它在解析的第一个字段上获得的 ID:return parseInt(this.u[0]); 如果我理解正确的话?就像我的情况一样,如果 JSON 字符串中的 ID 字段位置发生变化怎么办。

最佳答案

您的 JSON 是:

{
"title": "test",
"content": "test",
"id": 1,
"user": null,
"hash": null,
"created": 1379569937945,
"modified": 1379569937945,
"password": null,
"views": 0
}

只需使用 JavaScript objects 为它创建一个覆盖(即,一个零开销的 Java 对象,它精确地表示和映射您的 JSON 结构)和 JSNI语法,并使用 JsonUtils.safeEval()安全地评估负载并返回覆盖实例。

import com.google.gwt.core.client.JsonUtils;

public class YourFancyName extends JavaScriptObject {

/**
* Overlay types always have protected, zero-arg ctors.
*/
protected YourFancyName() { }

/**
* Safely evaluate the JSON payload and create the object instance.
*/
public static YourFancyName create(String json) {
return (YourFancyName) JsonUtils.safeEval(json);
}

/**
* Returns the title property.
*/
public native String getTitle() /*-{
return this.title;
}-*/;

/**
* Returns the id property.
*/
public native int getId() /*-{
return this.id;
}-*/;

// And the like...
}

关于java - 使用 GWT Overlay 类型将 JSON String 转换为 POJO,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18887230/

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