我想创建像这样的json字符串 -
{
"credentials": {
"name":"abc",
"password":"pass"
}
}
我创建了一个名为Credentials的Java类,其中包含“name”和“password”字段。 我在凭证对象中添加了名称和密码值。为了给出一个REST调用,我想在body部分发送json对象/字符串,如前所述。 但我的Json字符串/对象在json字符串中没有凭据名称。它看起来像这样 -
{
"name": "jamal11",
"password": "5test5@5"
}
下面是我将Credentials对象转换为JSON字符串的代码 -
credentials.setName(name);
credentials.setPassword(password);
//conversion of RequestParamDto object to JSON
ObjectWriter ow = new ObjectMapper().writer().withDefaultPrettyPrinter();
String requestParamJson = ow.writeValueAsString(credentials);
//add requestParam string to HttpPost
httpPost.setEntity(new StringEntity(requestParamJson, "UTF-8"));
我在这里遗漏了什么吗?请帮帮我。 谢谢!
答案 0 :(得分:0)
你应该让一个json对象放置一个参数,其中参数的键是“凭证”,参数的值是一个json数组,它是一个json对象。 或创建一个类,该类具有凭证对象作为标签在json中显示的属性
{
"credentials": [{
"name":"abc",
"password":"pass"
}]
}
示例:
class MyInterfaceList {
@JsonProperty("credentials")
private List<MyInterface> list;
public List<MyInterface> getList() {
return list;
}
public void setList(List<MyInterface> list) {
this.list = list;
}
}
final List<MyInterface> lists = new ArrayList<MyInterface>(4);
lists.add(new MyImpl("abc", "pass"));
MyInterfaceList listHolder = new MyInterfaceList();
listHolder.setList(lists);
final String json = mapper.writeValueAsString(listHolder);
Object Writer 这是更好的选择。使用已配置的ObjectWriter实例生成JSON。特别是,我们对withRootName方法感兴趣:
final List<MyInterface> lists = new ArrayList<MyInterface>(4);
lists.add(new MyImpl("abc", "pass"));
final ObjectWriter writer = mapper.writer().withRootName("credentials");
final String json = writer.writeValueAsString(lists);
答案 1 :(得分:0)
记得将json jar文件添加到项目库中
JSONObject a = new JSONObject();
a.accumulate("credentials", new JSONObject().put("name", "abc").put("password", "123"));