无法从json对象获取字符串。我得到了
Gson gson = new Gson();
Map<String, Object> resultMap = new HashMap<String, Object>();
resultMap = (Map<String, Object>)gson.fromJson(result, resultMap.getClass());
if (handler!=null) {
handler.responseReceived(new HashMap(resultMap),_queryName);
}
在另一个类中我需要获取JsonObject的元素
public void responseReceived(HashMap<String, Object> resp, String action) {
Log.e("!!!", action);
Log.e("!!!", "--------");
Log.e("!!!", resp.toString());
//Json Parsed, need just to get elements of jsonobject
}
现在如何从HashMap<String,Object>
resp?
答案 0 :(得分:1)
我们可以使用您当前的代码打印值。
使用map.keySet()。toString()从map打印String值 或者如果要打印对象,请使用map.values()。toString()
查看以下示例了解更多详情,
创建了一个小型对象类Employee
package com.zack.demo;
public class Employee {
private String name;
private int age;
private String gender;
public Employee(String name, int age, String gender)
{
this.name = name;
this.age = age;
this.gender = gender;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
}
GSONTest类具有不同的输入和输出格式,可以打印Map
中的值package com.zack.demo;
import java.util.HashMap;
import java.util.Map;
import com.google.gson.Gson;
public class GsonTest {
public static void main(String[] args) {
Gson gson = new Gson();
Map<String, Object> resultMap = new HashMap<String, Object>();
Employee o1 = new Employee("Test1", 10, "Male");
resultMap.put("T1", o1);
Employee o2 = new Employee("Test2", 20, "Male");
resultMap.put("T2", o2);
String result = gson.toJson(resultMap, resultMap.getClass());
System.out.println(result);
Map<String, Object> resultOutputMap = new HashMap<String, Object>();
resultOutputMap = (Map<String, Object>) gson.fromJson(result,
resultOutputMap.getClass());
System.out.println("Complete Map: "+ resultOutputMap.toString());
System.out.println("Values: "+resultOutputMap.values().toString());
System.out.println("Keys: "+resultOutputMap.keySet().toString());
}
}
上述课程的输出
{"T1":{"name":"Test1","age":10,"gender":"Male"},"T2":{"name":"Test2","age":20,"gender":"Male"}}
Complete Map: {T1={name=Test1, age=10.0, gender=Male}, T2={name=Test2, age=20.0, gender=Male}}
Values: [{name=Test1, age=10.0, gender=Male}, {name=Test2, age=20.0, gender=Male}]
Keys: [T1, T2]