2013-07-10 226 views
-5

什么是映射的最佳解决方案/反序列化JSON这样:的Json到Java对象的映射

{ "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; } 
+0

究竟是什么问题? – dougEfresh

+0

@dougEfresh问题是关于JSON直接映射到java。 –

+1

你可以尝试使用这个:http://json.org/java/或https://code.google.com/p/google-gson/ –

回答

1

我不知道库支持JSON数组之间的映射(“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()); 
+0

很好的解决方法,谢谢! – mgramin