尝试从嵌套在JSON中的数组中读取值

时间:2017-04-08 12:26:27

标签: java arrays json rest jackson

我一直在使用Jackson写一个Rest服务来提取响应值中的名称和sizeFromStorage。

我创建了以下类,试图这样做:

import java.util.List;

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;

@JsonIgnoreProperties(value = {"status", "header"})
public class Vaults {

private List<Object> response;

public Vaults(){

}

public Vaults(List<Object> response){
    this.response = response;
}

public List<Object> getResponse(){
    return response;
}

public void setResponse(List<Object> response) {
    this.response = response;
}

@Override
public String toString() {
    return "" + response;
}
}


import java.io.IOException;
import java.util.List;
import java.util.ArrayList;

import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.type.CollectionType;
import java.io.InputStream;

public class JacksonObjectModelTest {

public static void main(String[] args) throws IOException {
    String jsonFileName = "/JsonRead/json.json";
    List<Vaults> emps = new JacksonObjectModelTest().getVaultList(jsonFileName);
    System.out.println(emps.toString());
}

public ArrayList<Vaults> getVaultList(String jsonFileName) throws IOException {
    //read json file data to String
    InputStream inputStream = getClass().getResourceAsStream(jsonFileName);

    //create ObjectMapper instance
    ObjectMapper objectMapper = new ObjectMapper().enable(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY);

    //convert json string to object
    CollectionType collectionType = objectMapper.getTypeFactory().constructCollectionType(List.class, Vaults.class);
    ArrayList<Vaults> emps = objectMapper.readValue(inputStream, collectionType);
    return (ArrayList<Vaults>) emps;
}
}

{
  "status": "ok",
  "header": {
    "now": 1491545894581,
    "status": "ok",
    "requestId": "WOcvJsCoAmoAAESbkBYAAAB5"
  },
  "response": {
    "vault": [
      {
    "id": 20,
    "name": "Apple",
    "description": "",
    "sizeFromStorage": 95957225298,
    "storagePools": [
      {
        "storagePool": {
          "id": 1,
          "name": "storage-pool1",
          "sizeFromStorage": 95957225298,
          "generations": [
            {
              "generation": {
                "sequence": 0
              }
            }
          ]
        }
      }
    ]
  },
  {
    "id": 21,
    "name": "Banana",
    "description": "",
    "sizeFromStorage": 98957268244,
    "storagePools": [
      {
        "storagePool": {
          "id": 2,
          "name": "storage-pool1",
          "sizeFromStorage": 98957268244,
          "generations": [
            {
              "generation": {
                "sequence": 0
              }
            }
          ]
        }
      }
    ]
  },
]
  }
}

我得到的输出是:

[[{vaults=[{id=20, name=Apple, description=, sizeFromStorage=95957225298, storagePools=[{storagePool={id=1, name=storage-pool1, sizeFromStorage=5043, estimateUsableTotalLogicalSizeFromStorage=95957225298, generations=[{generation={sequence=0}}]}}]}, {id=20, name=Apple, description=, sizeFromStorage=95957225298, storagePools=[{storagePool={id=1, name=storage-pool1, sizeFromStorage=5043, estimateUsableTotalLogicalSizeFromStorage=95957225298, generations=[{generation={sequence=0}}]}}]}]]

但是,我想要做的是name和sizeFromStorage值。到目前为止,我已经设法剥离了前三个值。不幸的是,我现在卡住了,因为我对Rest服务或阅读JSON不是很熟悉。有没有什么方法可以深入研究JSON以获得我需要的东西或者我以错误的方式接近它?

其他信息: 自从发布我的原始问题后,我提出了这个问题(根据我在其他网站上看到的内容):

package JsonRead;

import java.io.File;
import java.io.IOException;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

public class JacksonTreeModel {
    public static void main(String[] args) {

        try{

            ObjectMapper mapper = new ObjectMapper();

            JsonNode root = mapper.readTree(new File("JsonRead/json.json"));

            JsonNode vaultsNode = root.path("response").path("vault");

            /*if(vaultsNode.isArray()){
                for(JsonNode node : vaultsNode){
                    String name = node.path("name").asText();
                    System.out.println("Array Name: " + name);
                }
            }*/

            for(JsonNode node : vaultsNode){
                String name = node.path("name").asText();
                String bytesUsed = node.path("sizeFromStorage").asText();
                System.out.println("Name: " + name + ", Bytes Used: " + bytesUsed);
            }

        } catch(IOException e){
                System.out.println("IO Exception " + e );
        }
    }
}

它适用于我想要的但是有更好的方法吗?

Will,谢谢你的回复。我会调查你的建议。

1 个答案:

答案 0 :(得分:1)

好的,我只是重新阅读你的问题。

建议您使用更有意义的自定义对象类型创建自己的VaultDAO对象,以用于响应集合。 Prvided你使用相同的变量名称(它看起来像你已知)然后它应该为你反序列化