我需要上传以下json:
[{"key":"value","key1":"value1"},
[{"innerkey":"innervalue","filename":"name"},{"innerkey":"innervalue","filename":"name"}]]
JsonArray内部的两个内键有两个文件需要上传。
我正在使用okhttp多段上传它们。
将普通字段添加为
multipart.addFormDataPart(key, value);
,文件添加为
multipart.addFormDataPart("filename", "image.jpeg", RequestBody.create(MediaType.parse("image/jpeg"), new File(path)));
在将json转换为hashmap并使用for循环添加部分之前,我已经上传了非嵌套json
MultipartBody.Builder multipart = new MultipartBody.Builder();
for (Map.Entry<String, String> entry : data.entrySet()) {
String key = entry.getKey();
String value = entry.getValue();
if(!key.equals("filePath")){
multipart.addFormDataPart(key, value);
}else{
String filename = "";
String type = MyUtility.getMimeType(key);
filename = key.substring(key.lastIndexOf("/") + 1);
multipart.addFormDataPart("fileName", filename, RequestBody.create(MediaType.parse(type), new File(key)));
}
}
新结构似乎很难处理,怎么办?
答案 0 :(得分:0)
请告诉我您正在寻找类似的东西
public static Map<String,String> convertToMap(Object yourJsonArrayOrJsonObject) throws Exception
{
HashMap<String, String> map = new HashMap<>();
processJSON(null, yourJsonArrayOrJsonObject, map);
return map;
}
private static void processJSON(String jsonKey, Object jsonItem, Map<String, String> map)
{
if (jsonItem instanceof JSONArray)
{
JSONArray array = (JSONArray) jsonItem;
for (Object arrayItem : array)
{
processJSON(null, arrayItem, map);
}
} else if (jsonItem instanceof JSONObject)
{
JSONObject json = (JSONObject) jsonItem;
Set<String> keys = json.keySet();
for (String key : keys)
{
processJSON(key, json.get(key), map);
}
} else
{
map.put(jsonKey, String.valueOf(jsonItem));
}
}