2012-04-05 81 views
1

任何人可以帮助我从一个JSON文件解析一个byte [] -机器人 - 解析的byte []使用杰克逊/ GSON JSON

JSON文件看起来是这样的:

{ 
    name:"test" 
    myImage:[67,78,....] 
    } 

我不想要创建一个新的JSONObject()并进行解析,因为这个文件可能会有多个图像并且系统内存不足。我想使用GSON/Jackson/JSONReader(android> 3.1),但它大多数似乎有getInt(),getString()对象。

如何解析字节[]本身到一个对象,我可以稍后转换为drawable。

我真的很感激任何帮助。

+0

顺便说一句,在Android 3.0的,你可以使用GSON https://code.google .com/p/google-gson/ – 2014-02-13 21:33:30

回答

0

你试过了什么?在杰克逊,你可以使用像POJO:

class Stuff { 
    public String name; 
    public byte[] myImage; 
} 

Stuff stuff = new ObjectMapper().readValue(new File("stuff.json"), Stuff.class); 

这应该工作。

但是,这种JSON序列化并不是典型的做法:将字节数组包含为base64编码数据更为常见。这是杰克逊将如何序列化它,如果您使用ObjectMapper.writeValue(...)。原因是base64编码将更紧凑,使用内存少于数组数组。

+0

我使用GSON解决了它 - 以这种方式: – user510164 2012-04-07 18:15:13

0

我解决它这样

InputStream instream = entity.getContent(); 
      Gson gson = new Gson(); 
      Reader reader = new InputStreamReader(instream); 
      JsonReader jsonReader = new JsonReader(jsonReader); 
       jsonReader.beginArray(); 
       while (jsonReader.hasNext()) { 
        MyCustomObject cobj = gson.fromJson(jReader, 
          MyCustomObject.class); 
        byte[] image = cobj.Image; 
        } 
0

JSONObject->getString().getBytes();

GSON/JsonReader->getString().getBytes();