2012-02-08 38 views
34

目前我正在开发一个带有webView前端的原生android应用程序。Gson将数组对象转换为json - Android

我有类似:

public class dataObject 
{ 
    int a; 
    String b; 
} 

和活性,

我已dataObject时的阵列,说dataObject时X [5];

现在我想在回调函数中将这5个dataObject传递给我的javascript webView接口作为JSON。

我通过网络看了一下,好像大多数教程都谈论如何转换fromJson()。没有太多关于toJson()。我发现一个教我dataObject.toJson(),会工作。

但我怎样才能通过所有5个数据对象?

+1

尝试'字符串JSON =新GSON()的toJSON(数据对象)',其中数据对象是DataObject中[] – reTs 2012-02-08 02:41:03

回答

81

下面是关于如何将Gson与对象列表一起使用的全面示例。这应该证明究竟如何转换到/从JSON,如何引用列表等

Test.java

import com.google.gson.Gson; 
import java.util.List; 
import java.util.ArrayList; 
import com.google.gson.reflect.TypeToken; 
import java.lang.reflect.Type; 


public class Test { 

    public static void main (String[] args) { 

    // Initialize a list of type DataObject 
    List<DataObject> objList = new ArrayList<DataObject>(); 
    objList.add(new DataObject(0, "zero")); 
    objList.add(new DataObject(1, "one")); 
    objList.add(new DataObject(2, "two")); 

    // Convert the object to a JSON string 
    String json = new Gson().toJson(objList); 
    System.out.println(json); 

    // Now convert the JSON string back to your java object 
    Type type = new TypeToken<List<DataObject>>(){}.getType(); 
    List<DataObject> inpList = new Gson().fromJson(json, type); 
    for (int i=0;i<inpList.size();i++) { 
     DataObject x = inpList.get(i); 
     System.out.println(x); 
    } 

    } 


    private static class DataObject { 
    private int a; 
    private String b; 

    public DataObject(int a, String b) { 
     this.a = a; 
     this.b = b; 
    } 

    public String toString() { 
     return "a = " +a+ ", b = " +b; 
    } 
    } 

} 

要编译:

javac -cp "gson-2.1.jar:." Test.java 

而且最后运行它:

java -cp "gson-2.1.jar:." Test 

请注意,如果您使用Windows,则必须在前两个命令中使用;切换:

在运行它,你应该看到下面的输出:

[{"a":0,"b":"zero"},{"a":1,"b":"one"},{"a":2,"b":"two"}] 
a = 0, b = zero 
a = 1, b = one 
a = 2, b = two 

请记住,这仅仅是一个命令行程序演示它是如何工作的,但同样的原则也适用内Android的环境(引用的jar库等)

+0

是行为相同的数据对象[],而不是列出? – lalitm 2014-05-10 06:46:32

+0

回答我自己的问题:是的,行为是一样的。 – lalitm 2014-05-10 07:38:53

+0

谢谢!它的工作原理 – 2014-12-30 13:16:20

0

我使用一个辅助类GSON列表反序列化的版本:

public List<E> getList(Class<E> type, JSONArray json) throws Exception { 
    Gson gsonB = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create(); 

    return gsonB.fromJson(json.toString(), new JsonListHelper<E>(type)); 
} 



public class JsonListHelper<T> implements ParameterizedType { 

    private Class<?> wrapped; 

    public JsonListHelper(Class<T> wrapped) { 
    this.wrapped = wrapped; 
    } 

    public Type[] getActualTypeArguments() { 
    return new Type[] {wrapped}; 
    } 

    public Type getRawType() { 
    return List.class; 
    } 

    public Type getOwnerType() { 
    return null; 
    } 

} 

使用

List<Object> objects = getList(Object.class, myJsonArray);