如何从json响应中读取键名称作为不区分大小写

时间:2017-02-20 12:05:40

标签: java json case-insensitive

以下是我的json格式代码:

  Uri selectedImage = data.getData();
        String[] filePathColumn = { MediaStore.Images.Media.DATA };
        Cursor cursor = getContentResolver().query(selectedImage,filePathColumn, null, null, null);
        cursor.moveToFirst();
        int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
        String picturePath = cursor.getString(columnIndex);
        cursor.close();
        ImageView imageView = (ImageView) findViewById(R.id.imgView);
        imageView.setImageBitmap(BitmapFactory.decodeFile(picturePath));

要将{ "topic": "Employee", "message": { "Id": "IND01", "data": { "salary": 50000 } } } topicmessageId等关键名称视为不区分大小写。如何从这个json响应体中获取密钥?

2 个答案:

答案 0 :(得分:1)

首先你的JSON不是vaild。我相信这是你的问题,它将解决你的其他问题。 试试

{
    "topic": "Employee",
    "message": {
        "Id ": "IND01",
        "data ": {

            "salary ": 50000
        }
    }
}

这是一个有效的JSON .Henceforth学习正确的JSON格式并使用任何json验证器来验证你的JSON。

答案 1 :(得分:0)

如果您可以将json转换为Map,则可以重新映射整个地图(递归地)将每个键转换为其小写值。

类似的东西:

public static Map<String,Object> convertToLowerCaseKeys(Map<String,Object> map){
    return map.entrySet().stream().collect(Collectors.toMap(e -> e.getKey().toLowerCase(), e -> {
        if(e.getValue() != null && e.getValue() instanceof Map){
            return convertToLowerCaseKeys((Map<String,Object>)e.getValue());
        }
        return e.getValue();
    }));
}

请注意,对地图的演员可能有些过于仓促,但为了简单起见,我已经将其删除了。

编辑:

在不区分大小写的情况下搜索(顶级)键:

public static Object getCaseInsensitive(Map<String,Object> map, String key){
    if(key == null){
        return map.get(null);
    }
    Optional<String> optional = map.keySet().stream().filter(e -> e != null && e.toLowerCase().equals(key.toLowerCase())).findAny();
    if(optional.isPresent()){
        return map.get(optional.get());
    }
    return null;
}