将字符串json解析为List <model>

时间:2017-12-12 18:20:02

标签: java android json parsing

我只是无法解决这个问题。我从服务器获取数据,将其保存在共享偏好设置key = data value = "[.. json]中。 屏幕截图中可以看到数据的结构和类型。

sample image

如何在List <User ..>中正确使用json。我使用这个代码,它使用jackson2库,但它不起作用。我收到了错误

  

JsonMappingException:无法从START_ARRAY标记中反序列化com.example.dmitriysamoilov.filipapp.model.UserContactListModel的实例

public List<UserContactListModel> getUserLocalContactsData() {
    List<UserContactListModel> listModels = new ArrayList<>();
    String json = "";

    sharedPreferences = context.getSharedPreferences(ReservedName.USER_LOCAL_CONTACTS_DATA,
            context.MODE_PRIVATE);

    if (sharedPreferences.contains("json")) {
        json = sharedPreferences.getString("json", "");
    }else return listModels;

    ObjectMapper mapper = new ObjectMapper();

    try {
        // Convert JSON string from file to Object
        UserContactListModel l  = mapper.readValue(json,UserContactListModel.class);


    } catch (JsonGenerationException e) {
        e.printStackTrace();
    } catch (JsonMappingException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    return listModels;
}

我明白逻辑不正确,但我无法想象很长时间

2 个答案:

答案 0 :(得分:0)

由于您的json是数组,请尝试以下

listModels  = Arrays.asList(mapper.readValue(json, UserContactListModel[].class));

答案 1 :(得分:0)

举一个简短的例子,试着找出你的结果。

String jsonArray = "[{\"brand\":\"ford\"}, {\"brand\":\"Fiat\"}]";

ObjectMapper objectMapper = new ObjectMapper();

List<Car> cars1 = objectMapper.readValue(jsonArray, new TypeReference<List<Car>>(){});

这里是您的代码 -

public List<UserContactListModel> getUserLocalContactsData() {
    List<UserContactListModel> listModels = new ArrayList<>();
    String json = "";

    sharedPreferences = context.getSharedPreferences(ReservedName.USER_LOCAL_CONTACTS_DATA,
            context.MODE_PRIVATE);

    if (sharedPreferences.contains("json")) {
        json = sharedPreferences.getString("json", "");
    }else return listModels;

    ObjectMapper mapper = new ObjectMapper();

    try {
        // Convert JSON string from file to Object
        listModels  = mapper.readValue(json,new TypeReference<List<UserContactListModel>>(){});


    } catch (JsonGenerationException e) {
        e.printStackTrace();
    } catch (JsonMappingException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    return listModels;
}