Toydor
Toydor

Reputation: 2327

gson with mixed read

I'm trying to read json with gson, but I can't get a "simple" gson example to work.

From: https://sites.google.com/site/gson/streaming

    public List<Message> readJsonStream(InputStream in) throws IOException {
      JsonReader reader = new JsonReader(new InputStreamReader(in, "UTF-8"));
      List<Message> messages = new ArrayList<Message>();
      reader.beginArray();
      while (reader.hasNext()) {
          Message message = gson.fromJson(reader, Message.class);
          messages.add(message);
      }
      reader.endArray();
      reader.close();
      return messages;
   }

Here's the problem, if I try with:

JsonReader reader;
Gson gson = new Gson();
gson.fromJson(reader,Program.class);

It doesn't even build.

The method fromJson(String, Class<T>) in the type Gson is not applicable for the arguments (JsonReader, Class<Program>)

There seems to be a method according to eclipse: fromJson(JsonReader arg0, Type arg1)

Upvotes: 2

Views: 1338

Answers (2)

Toydor
Toydor

Reputation: 2327

Replace

import android.util.JsonReader;   

with

import com.google.gson.stream.JsonReader 

did it! =)

Upvotes: 5

ProXamer
ProXamer

Reputation: 375

It is mentionned that the fromJson method accepts argument 0 as a String. Try to create a method that transforms the inputStream to a String.

static public String generateString(InputStream stream) {

        InputStreamReader reader = new InputStreamReader(stream);
        BufferedReader buffer = new BufferedReader(reader);
        StringBuilder sb = new StringBuilder();
        try { 
            String cur;   
            while ((cur = buffer.readLine()) != null) {   
                sb.append(cur).append("\n");  
            }  
        } catch (IOException e) {  
            e.printStackTrace();  
        }
        try {
            stream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return sb.toString(); 
    }

Upvotes: 1

Related Questions