java json转map(复杂混合类型list、map和string)

其中用到了instanceof,所需的jar包


看例子:

package json;

import java.util.List;
import java.util.Map;
import net.sf.json.JSONObject;

public class JsonTest {
public static void main(String[] args) {
//list string
String jsonString = "{\"fans\":[{\"name\":\"小王\",\"age\":7},{\"name\":\"小尼玛\",\"age\":10}],\"name\":\"王尼玛\"}";
Map map = JSONObject.fromObject(jsonString);
if (map.get("fans") instanceof List) {
for (Object object : (List)map.get("fans")) {
System.out.println(object);
}
}

if (map.get("name") instanceof String) {
System.out.println(map.get("name"));
}

//map list Integer
String jsonString2 = "{\"data\": {\"pages\": [ {\"comment\": \"just for test\"},{\"comment\": \"just for test\"}],\"total_count\": 2 },\"errcode\": 0}";
Map map2 = JSONObject.fromObject(jsonString2);
if (map2.get("data") instanceof Map) {
Map data = (Map) map2.get("data");
System.out.println(data.get("total_count"));
if (data.get("pages") instanceof List){
for (Object object : (List)data.get("pages")) {
System.out.println(object);
}
}
}

if (map2.get("errcode") instanceof Integer) {
System.out.println(map2.get("errcode"));
}
}
}


结果:

{"name":"小王","age":7}
{"name":"小尼玛","age":10}
王尼玛
2
{"comment":"just for test"}
{"comment":"just for test"}
0

你可能感兴趣的:(java,javaWeb)