This repository was archived by the owner on Dec 8, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathJsonHelper.java
More file actions
127 lines (106 loc) · 2.42 KB
/
JsonHelper.java
File metadata and controls
127 lines (106 loc) · 2.42 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
import com.loopj.android.http.RequestParams;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
public class JsonHelper
{
/**
* Convert JSONObject or JSONArray to RequestParams
* @param jsonObject
* @return
*/
public static RequestParams toRequestParams(JSONObject jsonObject)
{
return mapToRequestParams(objectToHashMap(jsonObject, ""));
}
/**
* Convert JSONObject to HashMap
* @param jsonObject
* @param prefix
* @return
*/
private static HashMap<String, String> objectToHashMap(JSONObject jsonObject, String prefix)
{
HashMap<String, String> hashMap = new HashMap<>();
Iterator<String> iterator = jsonObject.keys();
while (iterator.hasNext())
{
String key = iterator.next();
String tmpPrefix = prefix.isEmpty() ? key : prefix + "[" + key + "]";
try
{
Object value = jsonObject.get(key);
addParam(hashMap, tmpPrefix, value);
}
catch (JSONException e)
{
e.printStackTrace();
}
}
return hashMap;
}
/**
* Convert JSONArray to HashMap
* @param jsonArray
* @param prefix
* @return
*/
private static HashMap<String, String> arrayToHashMap(JSONArray jsonArray, String prefix)
{
HashMap<String, String> hashMap = new HashMap<>();
for(int i = 0; i < jsonArray.length(); i++)
{
String tmpPrefix = prefix + "[" + i + "]";
try
{
Object value = jsonArray.get(i);
addParam(hashMap, tmpPrefix, value);
}
catch(JSONException e)
{
e.printStackTrace();
}
}
return hashMap;
}
/**
* Convert HashMap to RequestParams
* @param map
* @return
*/
private static RequestParams mapToRequestParams(HashMap<String, String> map)
{
RequestParams params = new RequestParams();
for(Map.Entry<String, String> entry : map.entrySet())
{
params.add(entry.getKey(), entry.getValue());
}
return params;
}
/**
* Add param to HashMap
* @param params
* @param prefix
* @param value
*/
private static void addParam(HashMap<String, String> params, String prefix, Object value)
{
if(value instanceof JSONObject)
{
JSONObject obj = (JSONObject) value;
params.putAll(objectToHashMap(obj, prefix));
}
else if(value instanceof JSONArray)
{
JSONArray array = (JSONArray) value;
params.putAll(arrayToHashMap(array, prefix));
}
else
{
params.put(prefix, value.toString());
}
}
}