JSON应该如何存储如下所示的值

时间:2017-02-17 10:39:04

标签: java arrays json

我想将Json值存储到下面的数组中。

如果只是单一事件,

private static final String[] Eventname = {"Wedding"}
private static final String[][] Bid= {{"Studio 1"}}
private static final String[][] location= {{"Ernakulam"}}

如果有多个事件和多个投标人,

private static final String[]  Eventname = {"Wedding","Funeral"};
private static final String[][] Bid={{"Studio 1","Studio 2","Studio 3"},
                {"Studio 1","Studio 2","Studio 3"}}; 
private static final String[][] location= {{"Ernakulam"},{"Kollam"}}

我为例如:

创建了一个json
[
  {
    "Event": "Wedding",
    "Studios": [
      "Studio 1","Studio 2"
    ],
    "Location": ["Ernakulam","Bangalore"]
  },
  {
    "Event": "Birthday",
    "Studios": [
      "Studio 1"
    ],
    "Location": ["Ernakulam"]

  },
  {
    "Event": "Engagement",
    "Studios": [
       "Studio 1","Studio 2","Studio 2"
    ],
    "Location": ["Ernakulam","Bangalore","Angamaly"]
  }
]

但是我如何获得这个json值并将其存储在上面的数组中。

3 个答案:

答案 0 :(得分:1)

java中有多个json解析库 例如,你可以使用javax.json。

在这种情况下你可以做到

try(JsonReader jsonReader = Json.createReader(new StringReader(yourJsonString))){
 JsonArray arr = jsonReader.readArray();
 ... run through the entries in arr here and fill your arrays accordingly ...
}

但是我应该注意到你尝试创建的结构毫无意义,并且非常类似java。我建议你创建适当的类来代表Event,Venue和Bidding。这将使你的生活最终变得更容易......

答案 1 :(得分:1)

根据需要尝试

public class Test {

private static final String[]  EventName = new String[50];
private static final String[][] Bid = new String[50][50];
private static final String[][] location= new String[50][50];

public static void main(String[] args) throws ParseException {

        String sampleJSON = "[\n" +
            "  {\n" +
            "    \"Event\": \"Wedding\",\n" +
            "    \"Studios\": [\n" +
            "      \"Studio 1\",\"Studio 2\"\n" +
            "    ],\n" +
            "    \"EventObject\": [\"Ernakulam\",\"Bangalore\"]\n" +
            "  },\n" +
            "  {\n" +
            "    \"Event\": \"Birthday\",\n" +
            "    \"Studios\": [\n" +
            "      \"Studio 1\"\n" +
            "    ],\n" +
            "    \"EventObject\": [\"Ernakulam\"]\n" +
            "\n" +
            "  },\n" +
            "  {\n" +
            "    \"Event\": \"Engagement\",\n" +
            "    \"Studios\": [\n" +
            "       \"Studio 1\",\"Studio 2\",\"Studio 2\"\n" +
            "    ],\n" +
            "    \"EventObject\": [\"Ernakulam\",\"Bangalore\",\"Angamaly\"]\n" +
            "  }\n" +
            "]";


    Gson gson = new Gson();

    ArrayList<EventObject> eventObjectArrayList = gson.fromJson(sampleJSON, new TypeToken<List<EventObject>>(){}.getType());

    for (int i = 0; i < eventObjectArrayList.size(); i++) {

        EventName[i] = eventObjectArrayList.get(i).getEvent();

        for (int j = 0; j < eventObjectArrayList.get(i).getStudios().size(); j++) {
            Bid[i][j] = eventObjectArrayList.get(i).getStudios().get(j);
        }

        for (int k = 0; k < eventObjectArrayList.get(i).getLocation().size(); k++) {
            location[i][k] = eventObjectArrayList.get(i).getLocation().get(k);
        }

    }
}
}
  

您需要GSON jar com.google.code.gson:gson:2.2.4将其导入您的项目或在项目中将jar添加为lib。

     

这是您的EventObject类

public class EventObject implements Serializable {

String Event;
ArrayList<String> Studios;
ArrayList<String> Location;

public EventObject() {
}

public String getEvent() {
    return Event;
}

public void setEvent(String event) {
    Event = event;
}

public ArrayList<String> getStudios() {
    return Studios;
}

public void setStudios(ArrayList<String> studios) {
    Studios = studios;
}

public ArrayList<String> getLocation() {
    return Location;
}

public void setLocation(ArrayList<String> location) {
    Location = location;


 }
}

答案 2 :(得分:1)

使用Jackson,您可以为您的JSON编写自己的反序列化程序并按您的意愿阅读:

public static class Events {
    private final String[] event;
    private final String[][] bid;
    private final String[][] location;

    public Events(String[] event, String[][] bid, String[][] location) {
        this.event = event;
        this.bid = bid;
        this.location = location;
    }

    public String[] getEvent() {
        return event;
    }

    public String[][] getBid() {
        return bid;
    }

    public String[][] getLocation() {
        return location;
    }
}

private class EventsDeserializer extends StdDeserializer<Events> {
    protected EventsDeserializer() {
        super(Events.class);
    }

    @Override
    public Events deserialize(JsonParser p, DeserializationContext ctxt) throws IOException, JsonProcessingException {
        ArrayNode arrayNode = p.readValueAsTree();

        String[] events = new String[arrayNode.size()];
        String[][] bid = new String[arrayNode.size()][0];
        String[][] location = new String[arrayNode.size()][0];

        for (int i = 0; i < arrayNode.size(); i++) {
            JsonNode internalNode = arrayNode.get(i);
            events[i] = internalNode.get("Event").asText();
            bid[i] = convertToArray(internalNode.get("Studios"));
            location[i] = convertToArray(internalNode.get("Location"));
        }

        return new Events(events, bid, location);
    }

    private String[] convertToArray(JsonNode childNode) {
        String[] locations = new String[0];
        if (childNode != null && childNode.isArray()) {
            ArrayNode locationNodeArrayNode = (ArrayNode) childNode;
            locations = new String[locationNodeArrayNode.size()];
            for (int j = 0; j < locations.length; j++) {
                locations[j] = locationNodeArrayNode.get(j).asText();
            }
        }
        return locations;
    }
}

@Test
public void test() throws Exception {
    SimpleModule sm = new SimpleModule();
    sm.addDeserializer(Events.class, new EventsDeserializer());

    ObjectMapper mapper = new ObjectMapper();
    mapper.registerModule(sm);

    Events events = mapper.readValue(JSON, Events.class);
    System.out.println(events);
}

但我建议你让你的内部结构更接近原来的Json:

  public static class Event {
    @JsonProperty("Event")
    private String event;
    @JsonProperty("Studios")
    private List<String> bid;
    @JsonProperty("Location")
    private List<String> location;

    public String getEvent() {
        return event;
    }

    public void setEvent(String event) {
        this.event = event;
    }

    public List<String> getLocation() {
        return location;
    }

    public void setLocation(List<String> location) {
        this.location = location;
    }
}

@Test
public void test() throws Exception {
    ObjectMapper mapper = new ObjectMapper();
    Event[] jsonEvent = mapper.readValue(JSON, Event[].class);
    System.out.println(events);
}

正如您所看到的,如果您提供正确的映射,杰克逊能够为您完成所有工作。它可以帮助您获得更清晰的代码,为每个节点分别设置实例,并且不要将所有对象混合在一个数组中,这看起来像是糟糕的设计。