Json到java对象的映射

时间:2013-07-10 18:14:47

标签: java json deserialization

映射/反序列化此json的最佳解决方案是什么:

 { "columns" : [ "name", "description", "id" ], "data" : [ [ "Train", "Train desc", 36 ], [ "Ship", "Ship desc", 35 ], [ "Plane", "Plane desc", 34 ] ] } 

到这个类的对象列表:

class Transport { String id; String name; String description; }

1 个答案:

答案 0 :(得分:1)

我不知道支持JSON Arrays(“data”是数组数组)和Java对象字段之间映射的库。

gson库允许您将JSON数组映射到java String数组的数组中,但是您必须将其转换为对象模型。 您可以将JSON解析为此对象:

class DataWrapper
{
    String[] columns;
    String[][] data;
}

另一个解决方案是使用JSonReader并使用此类流出对象:

import java.io.IOException;
import java.io.Reader;
import java.util.Iterator;

import com.google.gson.stream.JsonReader;

public class TransportJSonReader implements Iterator<Transport> {

protected JsonReader jsonReader;

public TransportJSonReader(Reader reader) throws IOException
{
    jsonReader = new JsonReader(reader);
    jsonReader.beginObject();

    //columns
    jsonReader.nextName();
    jsonReader.skipValue();

    //data
    jsonReader.nextName();
    jsonReader.beginArray();

}

@Override
public boolean hasNext() {
    try {
        return jsonReader.hasNext();
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

@Override
public Transport next() {
    if (!hasNext()) throw new IllegalStateException();

    try {
        jsonReader.beginArray();
        String name = jsonReader.nextString();
        String description = jsonReader.nextString();
        String id = jsonReader.nextString();
        jsonReader.endArray();
        return new Transport(id, name, description);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

@Override
public void remove() {
    throw new UnsupportedOperationException();
}

}

它是一个迭代器,所以你可以这样使用它:

    TransportJSonReader reader = new TransportJSonReader(new StringReader(json));
    while(reader.hasNext()) System.out.println(reader.next());