创建一个json数组

时间:2017-03-30 18:15:28

标签: java json jackson

我正在编写一个代码,其中必须有一个在json中生成的主数组。我的代码如下。

我的 pojos

JsonCreator.java

package com.createjson;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.fasterxml.jackson.annotation.JsonAnyGetter;
import com.fasterxml.jackson.annotation.JsonAnySetter;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;

@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonPropertyOrder({ "EntityLabels", "ExampleText", "SelectedIntentName" })
public class Jsoncreator {

    @JsonProperty("EntityLabels")
    private List<EntityLabel> entityLabels = null;
    @JsonProperty("ExampleText")
    private String exampleText;
    @JsonProperty("SelectedIntentName")
    private String selectedIntentName;
    @JsonIgnore
    private Map<String, Object> additionalProperties = new HashMap<String, Object>();

    @JsonProperty("EntityLabels")
    public List<EntityLabel> getEntityLabels() {
        return entityLabels;
    }

    @JsonProperty("EntityLabels")
    public void setEntityLabels(List<EntityLabel> entityLabels) {
        this.entityLabels = entityLabels;
    }

    @JsonProperty("ExampleText")
    public String getExampleText() {
        return exampleText;
    }

    @JsonProperty("ExampleText")
    public void setExampleText(String exampleText) {
        this.exampleText = exampleText;
    }

    @JsonProperty("SelectedIntentName")
    public String getSelectedIntentName() {
        return selectedIntentName;
    }

    @JsonProperty("SelectedIntentName")
    public void setSelectedIntentName(String selectedIntentName) {
        this.selectedIntentName = selectedIntentName;
    }

    @JsonAnyGetter
    public Map<String, Object> getAdditionalProperties() {
        return this.additionalProperties;
    }

    @JsonAnySetter
    public void setAdditionalProperty(String name, Object value) {
        this.additionalProperties.put(name, value);
    }

}

EntityLabel.java

package com.createjson;

import java.util.HashMap;
import java.util.Map;
import com.fasterxml.jackson.annotation.JsonAnyGetter;
import com.fasterxml.jackson.annotation.JsonAnySetter;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;

@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonPropertyOrder({ "StartToken", "EntityType", "EndToken" })
public class EntityLabel {

    @JsonProperty("StartToken")
    private int startToken;
    @JsonProperty("EntityType")
    private String entityType;
    @JsonProperty("EndToken")
    private int endToken;
    @JsonIgnore
    private Map<String, Object> additionalProperties = new HashMap<String, Object>();

    @JsonProperty("StartToken")
    public int getStartToken() {
        return startToken;
    }

    @JsonProperty("StartToken")
    public void setStartToken(int startToken) {
        this.startToken = startToken;
    }

    @JsonProperty("EntityType")
    public String getEntityType() {
        return entityType;
    }

    @JsonProperty("EntityType")
    public void setEntityType(String entityType) {
        this.entityType = entityType;
    }

    @JsonProperty("EndToken")
    public int getEndToken() {
        return endToken;
    }

    @JsonProperty("EndToken")
    public void setEndToken(int endToken) {
        this.endToken = endToken;
    }

    @JsonAnyGetter
    public Map<String, Object> getAdditionalProperties() {
        return this.additionalProperties;
    }

    @JsonAnySetter
    public void setAdditionalProperty(String name, Object value) {
        this.additionalProperties.put(name, value);
    }

}

主要类

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.config.ConfigDetails;
import com.createjson.EntityLabel;
import com.createjson.Jsoncreator;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

public class dummy {

    public static void main(String[] args) throws JsonProcessingException {
        Jsoncreator jsoncreator = null;
        EntityLabel label;
        List<EntityLabel> entityLabelList;
        ObjectMapper objectMapper;
        List<String> matchList;
        String[] lines = { "What is (Jim)'s gift (limit)? <=> Personname <=> Amount::Spent",
                "What is (John)'s gift (limit)? <=> Personname <=> Amount::Spent" };
        // check if the text has entities
        for (String line : lines) {
            entityLabelList = new ArrayList<EntityLabel>();

            if (line.contains("<=>")) {
                String[] example_split = line.split("<=>", 2);
                // System.out.println("String is " + example_split[1]);
                if (example_split[0].length() > 1) {
                    String[] example_entity = example_split[1].split("<=>");
                    int entities_count = 0;
                    int startPosition;
                    int endPosition = 0;
                    matchList = new ArrayList<>();
                    Pattern regex = Pattern.compile("\\((.*?)\\)");
                    Matcher regexMatcher = regex.matcher(line);
                    jsoncreator = new Jsoncreator();
                    while (regexMatcher.find()) {
                        startPosition = regexMatcher.start() + 1;
                        endPosition = regexMatcher.end() - 1;

                        matchList.add(regexMatcher.group(1));
                        label = new EntityLabel();

                        label.setStartToken(startPosition);
                        label.setEntityType(example_entity[entities_count].toString());
                        label.setEndToken(endPosition);
                        entityLabelList.add(label);

                        objectMapper = new ObjectMapper();
                        TestCasesString = objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(label);
                        jsoncreator.setEntityLabels(entityLabelList);

                        entities_count++;
                    }

                }
            }
            objectMapper = new ObjectMapper();
            System.out.println(objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(jsoncreator));

        }

    }
}

当我运行这个程序时,创建了两个对象,但我想创建一个songle对象。

我当前的O / P

{
  "EntityLabels" : [ {
    "StartToken" : 9,
    "EntityType" : " Personname ",
    "EndToken" : 12
  }, {
    "StartToken" : 22,
    "EntityType" : " Amount::Spent",
    "EndToken" : 27
  } ]
}
{
  "EntityLabels" : [ {
    "StartToken" : 9,
    "EntityType" : " Personname ",
    "EndToken" : 13
  }, {
    "StartToken" : 23,
    "EntityType" : " Amount::Spent",
    "EndToken" : 28
  } ]
}

我预期的O / P

[{
  "EntityLabels" : [ {
    "StartToken" : 9,
    "EntityType" : " Personname ",
    "EndToken" : 12
  }, {
    "StartToken" : 22,
    "EntityType" : " Amount::Spent",
    "EndToken" : 27
  } ]
},
{
  "EntityLabels" : [ {
    "StartToken" : 9,
    "EntityType" : " Personname ",
    "EndToken" : 13
  }, {
    "StartToken" : 23,
    "EntityType" : " Amount::Spent",
    "EndToken" : 28
  } ]
}]

请让我知道我该怎么做。

由于

1 个答案:

答案 0 :(得分:0)

如果你想要一个数组,你需要序列化一个列表,就像你已经使用entityLabels一样。每个jsoncreator对象都将为该实例创建一个json表示,只需将它们保存在列表中并序列化即可。

类似的东西:

public class dummy {

  public static void main(String[] args) throws JsonProcessingException {
      List<Jsoncreator> objectsToSerialise = new ArrayList<>();

      ... your code

    // check if the text has entities
    for (String line : lines) {

      ... your code

      objectsToSerialise.add(jsonCreator);
    }

    objectMapper = new ObjectMapper();
    System.out.println(objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(objectsToSerialise));

  }
}

希望你明白这一点。

Jackson – Unmarshall to Collection/Array