Skip to content

Commit ac78ada

Browse files
committed
Add getStringList from JSON
1 parent dd1f9e0 commit ac78ada

File tree

1 file changed

+68
-1
lines changed

1 file changed

+68
-1
lines changed

src/cn/trinea/android/common/util/JSONUtils.java

Lines changed: 68 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,9 @@
11
package cn.trinea.android.common.util;
22

3+
import java.util.ArrayList;
34
import java.util.HashMap;
45
import java.util.Iterator;
6+
import java.util.List;
57
import java.util.Map;
68

79
import org.json.JSONArray;
@@ -372,10 +374,75 @@ public static String[] getStringArray(String jsonData, String key, String[] defa
372374
}
373375
}
374376

377+
/**
378+
* get String list from jsonObject
379+
*
380+
* @param jsonObject
381+
* @param key
382+
* @param defaultValue
383+
* @return <ul>
384+
* <li>if jsonObject is null, return defaultValue</li>
385+
* <li>if key is null or empty, return defaultValue</li>
386+
* <li>if {@link JSONObject#getJSONArray(String)} exception, return defaultValue</li>
387+
* <li>if {@link JSONArray#getString(int)} exception, return defaultValue</li>
388+
* <li>return string array</li>
389+
* </ul>
390+
*/
391+
public static List<String> getStringList(JSONObject jsonObject, String key, List<String> defaultValue) {
392+
if (jsonObject == null || StringUtils.isEmpty(key)) {
393+
return defaultValue;
394+
}
395+
396+
try {
397+
JSONArray statusArray = jsonObject.getJSONArray(key);
398+
if (statusArray != null) {
399+
List<String> list = new ArrayList<String>();
400+
for (int i = 0; i < statusArray.length(); i++) {
401+
list.add(statusArray.getString(i));
402+
}
403+
return list;
404+
}
405+
} catch (JSONException e) {
406+
if (isPrintException) {
407+
e.printStackTrace();
408+
}
409+
return defaultValue;
410+
}
411+
return defaultValue;
412+
}
413+
414+
/**
415+
* get String list from jsonData
416+
*
417+
* @param jsonData
418+
* @param key
419+
* @param defaultValue
420+
* @return <ul>
421+
* <li>if jsonObject is null, return defaultValue</li>
422+
* <li>if jsonData {@link JSONObject#JSONObject(String)} exception, return defaultValue</li>
423+
* <li>return {@link JSONUtils#getStringList(JSONObject, String, List)}</li>
424+
* </ul>
425+
*/
426+
public static List<String> getStringList(String jsonData, String key, List<String> defaultValue) {
427+
if (StringUtils.isEmpty(jsonData)) {
428+
return defaultValue;
429+
}
430+
431+
try {
432+
JSONObject jsonObject = new JSONObject(jsonData);
433+
return getStringList(jsonObject, key, defaultValue);
434+
} catch (JSONException e) {
435+
if (isPrintException) {
436+
e.printStackTrace();
437+
}
438+
return defaultValue;
439+
}
440+
}
441+
375442
/**
376443
* get JSONObject from jsonObject
377444
*
378-
* @param jsonObject<em><em></em></em>
445+
* @param jsonObject
379446
* @param key
380447
* @param defaultValue
381448
* @return <ul>

0 commit comments

Comments
 (0)