从POJO创建JSONObject

rta7y2nd  于 5个月前  发布在  其他
关注(0)|答案(9)|浏览(60)

我创建了一个简单的POJO:

public class LoginPojo {
    private String login_request = null;
    private String email = null;
    private String password = null;

    // getters, setters
}

字符串
经过一番搜索,我找到了这个:JSONObject jsonObj = new JSONObject( loginPojo );
但我得到了错误:

The constructor JSONObject(LoginPojo) is undefined


我找到了另一个解决办法:

JSONObject loginJson = new JSONObject();
loginJson.append(loginPojo);


但这种方法并不存在。
如何将POJO转换为JSON?

daupos2t

daupos2t1#

使用java Gson API

Gson gson = new GsonBuilder().create();
String json = gson.toJson(obj);// obj is your object

字符串
然后你可以从这个json String创建一个JSONObject,像这样:

JSONObject jsonObj = new JSONObject(json);


查看Gson user guideSIMPLE GSON EXAMPLE以了解更多信息。

7bsow1i6

7bsow1i62#

可以从POJO获取(gson)JsonObject:

JsonElement element = gson.toJsonTree(userNested);
JsonObject object = element.getAsJsonObject();

字符串
然后你可以用object.entrySet()来查找所有的树。
这是GSON中唯一一种绝对自由的方式,可以动态设置您想要查看的字段。

a1o7rhls

a1o7rhls3#

Jackson提供了JSON解析器/JSON生成器作为基础构建块;并添加了强大的数据绑定器(JSON <->POJO)和树模型作为可选的附加块。这意味着您可以读取和写入JSON作为令牌流(流API),作为普通旧Java对象(POJO,数据绑定)或作为树(树模型)。for more reference
您必须添加jackson-core-asl-x.x.x.jarjackson-mapper-asl-x.x.x.jar库来在项目中配置Jackson
修改代码:

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"}

字符串

vktxenjb

vktxenjb4#

JSONObject input = new JSONObject(pojo);

字符串
这与最新版本。

<dependency>
    <groupId>org.json</groupId>
    <artifactId>json</artifactId>
    <version>20180130</version>
</dependency>

6qftjkof

6qftjkof5#

你也可以使用project lombok和Gson重写toString函数。它自动包含builder,getter和setter,以简化数据分配,如下所示:

User user = User.builder().username("test").password("test").build();

字符串
在下面的示例类中查找:

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);
    }
}

7uhlpewt

7uhlpewt6#

您可以使用以下解决方案:

ObjectMapper mapper = new ObjectMapper();
String str = mapper.writeValueAsString(loginPojo);
JSONObject jsonObject = new JSONObject(str);

字符串

zaq34kh6

zaq34kh67#

我在我的项目中使用Jackson,但我认为你需要一个空的构造函数。

public LoginPojo(){
}

字符串

wkyowqbh

wkyowqbh8#

您可以使用

<dependency>
   <groupId>com.alibaba</groupId>
   <artifactId>fastjson</artifactId>
   <version>1.2.13</version>
 </dependency>

字符串
创建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();
}


将注解添加到POJO类中,如下所示:

@JSONField(name = "DATE OF BIRTH")
private String dateOfBirth;
etc...


然后您可以简单地使用:用途:

@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());
}


您可以在以下网站上找到更完整的教程:https://www.baeldung.com/fastjson

kjthegm6

kjthegm69#

简单的解决方案,Jackson和这些版本的JSONObject只接受Map作为构造函数参数:

ObjectMapper objectMapper = new ObjectMapper();
JSONObject jsonObject = new JSONObject(objectMapper.convertValue(pojo, Map.class));

字符串

相关问题