Как перебрать JSONArray, в котором есть JSONArray и JSONObject внутри Java 8 - PullRequest
0 голосов
/ 09 апреля 2019

Может ли кто-нибудь сказать мне, как перебрать JSONArray, который возвращает и JSONArray и JSONObject в нем.Я попробовал приведенный ниже код, и я получаю ошибку, как показано ниже.

com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize instance of 'com.example.jsonarr.pojoClass[]' out of START_OBJECT token

Код

List<pojoClass> pojoClassList = new ArrayList();
JSONArray jsonArrayList = new JSONArray( jsonResponse );
ObjectMapper objectMapper = new ObjectMapper(  );
pojoClassList = (List)objectMapper.readValue(jsonArrayList.toString(),
                        objectMapper.getTypeFactory().constructCollectionType(List.class, pojoClass[].class));

JSONArray

[
  {
  "Key1": "Value1",
  "Key2": "Value2",
  "Key3": "Value3",
  "Value1_tim":       {
     "amVal": 0,
     "pmVal": "0"
    }
  },
  [   {
  "Key1": "Value1",
  "Key2": "Value2",
  "Key3": "Value3",
  "Value1_tim":       {
     "amVal": 0,
     "pmVal": "0"
  }
  }]
]

С нормальным для цикла.

for ( int i = 0; i < jsonArrayList.length(); i++ ) {
     JSONObject jsonObject = jsonArrayList.optJSONObject( i );
     if ( jsonObject != null ) {
        pojoClass = objectMapper.readValue( jsonObject.toString(), PojoClass.class );
           }
     if ( jsonObject == null ) {
        JSONArray jsonArrayInner = new JSONArray( jsonArrayList.getJSONArray( i ).toString() );
        for ( int j = 0; j < jsonArrayInner.length(); j++ ) {
         JSONObject jsonObject1 = jsonArrayList.optJSONObject( j );
           if ( jsonObject1 != null ) {
            pojoClass = objectMapper.readValue( jsonObject1.toString(), PojoClass.class );
                 }
             }
         }
    pojoClassList.add( pojoClass );
  }

Как мне сделать это с Java 8?

1 Ответ

0 голосов
/ 10 апреля 2019

Если вы используете Jackson ObjectMapper, попробуйте использовать функцию ACCEPT_SINGLE_VALUE_AS_ARRAY, которая позволяет рассматривать отдельные элементы как one-element-array. Ниже вы можете найти простой пример того, как читать JSON в список Pojo классов:

import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.type.CollectionType;

import java.io.File;
import java.util.List;
import java.util.stream.Collectors;

public class JsonApp {

    public static void main(String[] args) throws Exception {
        File jsonFile = new File("./resource/test.json").getAbsoluteFile();

        ObjectMapper mapper = new ObjectMapper();
        mapper.enable(SerializationFeature.INDENT_OUTPUT);
        mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
        mapper.enable(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY);

        CollectionType collectionType0 = mapper.getTypeFactory().constructCollectionType(List.class, Pojo.class);
        CollectionType collectionType1 = mapper.getTypeFactory().constructCollectionType(List.class, collectionType0);
        List<List<Pojo>> list = mapper.readValue(jsonFile, collectionType1);

        List<Pojo> pojos = list.stream()
                .flatMap(List::stream)
                .collect(Collectors.toList());
        System.out.println(pojos);
    }
}

class Pojo {

    @JsonProperty("Key1")
    private String key1;

    // getters, setters, toString
}

Над отпечатками кодов:

[Pojo{key1='Value1'}, Pojo{key1='Value1-1'}]
...