java - 如何正确地将项目添加到 JSON 对象?
问题描述
1)下面附上更新的代码已根据我的需要更改了文件名:大多数错误在于TestObjectToJson方法。输出:想要返回 json 对象
''' }'''
2)另一种调用此json输出并仅返回接收到的id输出的方法:134
解决方案
终极更新
// Root.java
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
import java.util.List;
@JsonPropertyOrder({"received_id", "target", "legs"})
public class Root {
private long receivedId;
private String target;
private List<Leg> legs;
public long getReceivedId() { return receivedId; }
public void setReceivedId(long id) { this.receivedId = id; }
public String getTarget() { return target; }
public void setTarget(String t) { this.target = t; }
public List<Leg> getLegs() { return legs; }
public void setLegs(List<Leg> legs) { this.legs = legs; }
}
// Leg.java
public class Leg {
private long receivedGroupId;
private String status;
public long getReceivedGroupId() { return receivedGroupId; }
public void setReceivedGroupId(long id) { this.receivedGroupId = id; }
public String getStatus() { return status; }
public void setStatus(String st) { this.status = st; }
}
// Test.java
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.PropertyNamingStrategy;
import java.util.Arrays;
public class Test {
public static void main(String[] args) throws JsonProcessingException {
ObjectMapper mapper = new ObjectMapper()
.setPropertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE);
Root root = new Root();
root.setReceivedId(134L);
root.setTarget("none");
Leg leg = new Leg();
leg.setReceivedGroupId(234L);
leg.setStatus("active");
root.setLegs(Arrays.asList(leg));
String json = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(root);
System.out.println(json);
}
}
// output
{
"received_id" : 134,
"target" : "none",
"legs" : [ {
"received_group_id" : 234,
"status" : "active"
} ]
}
推荐阅读
- ssh - 如何将现有的 bitbucket SSH 帐户添加到 Xcode 9?
- sql-server - TSQL 根据开始和结束日期生成月份
- sql - Does this EXPLAIN indicate why Postgres query so slow
- python - numpy stack to 2d array, select by index from another stack
- android - 改变开关位置
- node.js - Date query works in Mongo shell but not from Node
- ruby-on-rails - 在 Rspec 中配置登录助手
- laravel - How to add package views to master view in Laravel?
- nginx - 如何在链式proxy_pass中转发nginx代理协议
- ruby-on-rails - 设计登录时的 URL 生成错误(缺少必需的键:id)