首页 > 解决方案 > 如何正确地将项目添加到 JSON 对象?

问题描述

1)下面附上更新的代码已根据我的需要更改了文件名:大多数错误在于TestObjectToJson方法。输出:想要返回 json 对象

''' }'''

2)另一种调用此json输出并仅返回接收到的id输出的方法:134

标签: javajson

解决方案


终极更新

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

推荐阅读