Java 从 POJO 创建 JSONObject
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27036857/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Create JSONObject from POJO
提问by Mulgard
I created a simple POJO:
我创建了一个简单的 POJO:
public class LoginPojo {
private String login_request = null;
private String email = null;
private String password = null;
// getters, setters
}
After some searching I found this: JSONObject jsonObj = new JSONObject( loginPojo );
经过一番搜索,我发现了这个: JSONObject jsonObj = new JSONObject( loginPojo );
But with this I got the error:
但是有了这个我得到了错误:
The constructor JSONObject(LoginPojo) is undefined
I found another solution:
我找到了另一个解决方案:
JSONObject loginJson = new JSONObject();
loginJson.append(loginPojo);
But this method does not exist.
但是这种方法不存在。
So how can I convert my POJO into a JSON?
那么如何将我的 POJO 转换为 JSON?
采纳答案by cн?dk
Simply use the java GsonAPI:
只需使用 java GsonAPI:
Gson gson = new GsonBuilder().create();
String json = gson.toJson(obj);// obj is your object
And then you can create a JSONObject
from this json String
, like this:
然后你可以JSONObject
从这个 json创建一个String
,像这样:
JSONObject jsonObj = new JSONObject(json);
Take a look at Gson user guideand this SIMPLE GSON EXAMPLEfor more information.
查看Gson 用户指南和这个简单的 GSON 示例以获取更多信息。
回答by Dave
I use Hymanson in my project, but I think that u need a empty constructor.
我在我的项目中使用 Hymanson,但我认为你需要一个空的构造函数。
public LoginPojo(){
}
回答by atish shimpi
Hymanson
provides JSON parser/JSON generator as foundational building block; and adds a powerful Databinder (JSON<->POJO) and Tree Model as optional add-on blocks. This means that you can read and write JSON either as stream of tokens (Streaming API), as Plain Old Java Objects (POJOs, databind) or as Trees (Tree Model). for more reference
Hymanson
提供 JSON 解析器/JSON 生成器作为基础构建块;并添加了一个强大的数据绑定器 (JSON<->POJO) 和树模型作为可选的附加块。这意味着您可以将 JSON 作为令牌流(流 API)、普通旧 Java 对象(POJO、数据绑定)或树(树模型)读取和写入。更多参考
You have to add Hymanson-core-asl-x.x.x.jar
, Hymanson-mapper-asl-x.x.x.jar
libraries to configure Hymanson
in your project.
你必须添加Hymanson-core-asl-x.x.x.jar
,Hymanson-mapper-asl-x.x.x.jar
库来配置Hymanson
你的项目。
Modified Code :
修改后的代码:
LoginPojo loginPojo = new LoginPojo();
ObjectMapper mapper = new ObjectMapper();
try {
mapper.setVisibility(JsonMethod.FIELD, Visibility.ANY);
// Setting values to POJO
loginPojo.setEmail("[email protected]");
loginPojo.setLogin_request("abc");
loginPojo.setPassword("abc");
// Convert user object to json string
String jsonString = mapper.writeValueAsString(loginPojo);
// Display to console
System.out.println(jsonString);
} catch (JsonGenerationException e){
e.printStackTrace();
} catch (JsonMappingException e){
e.printStackTrace();
} catch (IOException e){
e.printStackTrace();
}
Output :
{"login_request":"abc","email":"[email protected]","password":"abc"}
回答by Gangnus
It is possible to get a (gson) JsonObject from POJO:
可以从 POJO 获取(gson)JsonObject:
JsonElement element = gson.toJsonTree(userNested);
JsonObject object = element.getAsJsonObject();
After that you can take object.entrySet()
and look up all the tree.
之后,您可以object.entrySet()
查看并查看所有树。
It is the only absolutely free way in GSON to set dynamically what fields you want to see.
这是 GSON 中唯一一种完全免费的方式来动态设置您想要查看的字段。
回答by Stalin Gino
JSONObject input = new JSONObject(pojo);
This worked with latest version.
这适用于最新版本。
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20180130</version>
</dependency>
回答by Dezso Gabos
You can use
您可以使用
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.13</version>
</dependency>
To create a JSON object:
要创建 JSON 对象:
@Test
public void whenGenerateJson_thanGenerationCorrect() throws ParseException {
JSONArray jsonArray = new JSONArray();
for (int i = 0; i < 2; i++) {
JSONObject jsonObject = new JSONObject();
jsonObject.put("AGE", 10);
jsonObject.put("FULL NAME", "Doe " + i);
jsonObject.put("DATE OF BIRTH", "2016/12/12 12:12:12");
jsonArray.add(jsonObject);
}
String jsonOutput = jsonArray.toJSONString();
}
Add the annotations to your POJO class like so:
将注释添加到您的 POJO 类中,如下所示:
@JSONField(name = "DATE OF BIRTH")
private String dateOfBirth;
etc...
Then you can simply use:
然后你可以简单地使用:
@Test
public void whenJson_thanConvertToObjectCorrect() {
Person person = new Person(20, "John", "Doe", new Date());
String jsonObject = JSON.toJSONString(person);
Person newPerson = JSON.parseObject(jsonObject, Person.class);
assertEquals(newPerson.getAge(), 0); // if we set serialize to false
assertEquals(newPerson.getFullName(), listOfPersons.get(0).getFullName());
}
You can find a more complete tutorial on the following site: https://www.baeldung.com/fastjson
您可以在以下站点上找到更完整的教程:https: //www.baeldung.com/fastjson
回答by Carlos Cavero
You can also use project lombokwith Gson overriding toString function. It automatically includes builders, getters and setters in order to ease the data assignment like this:
您还可以使用带有 Gson 覆盖 toString 函数的 lombok项目。它自动包含构建器、getter 和 setter 以简化数据分配,如下所示:
User user = User.builder().username("test").password("test").build();
Find below the example class:
在示例类下面找到:
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import com.google.gson.Gson;
@Data
@Builder(toBuilder = true)
@AllArgsConstructor
@NoArgsConstructor
public class User {
/* User name. */
private String username;
/* Password. */
private String password;
@Override
public String toString() {
return new Gson().toJson(this, User.class);
}
public static User fromJSON(String json) {
return new Gson().fromJson(json, User.class);
}
}
回答by Belal R
Simply you can use the below solution:
您只需使用以下解决方案:
ObjectMapper mapper = new ObjectMapper();
String str = mapper.writeValueAsString(loginPojo);
JSONObject jsonObject = new JSONObject(str);