// Copyright 2012 Square, Inc.
package retrofit.http;

import com.google.gson.Gson;
import com.google.gson.JsonParseException;
import retrofit.io.MimeType;
import retrofit.io.TypedBytes;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.lang.reflect.Type;

/**
 * A {@link Converter} which uses GSON for serialization and deserialization of entities.
 *
 * @author Jake Wharton (jw@squareup.com)
 */
public class GsonConverter implements Converter {
  private final Gson gson;

  public GsonConverter(Gson gson) {
    this.gson = gson;
  }

  @Override public Object to(byte[] body, Type type) throws ConversionException {
    try {
      // TODO use actual encoding
      InputStreamReader isr = new InputStreamReader(new ByteArrayInputStream(body), "UTF-8");
      return gson.fromJson(isr, type);
    } catch (IOException e) {
      throw new ConversionException(e);
    } catch (JsonParseException e) {
      throw new ConversionException(e);
    }
  }

  @Override public TypedBytes from(Object object) {
    return new JsonTypedBytes(gson, object);
  }

  private static class JsonTypedBytes implements TypedBytes {
    private final String json;

    JsonTypedBytes(Gson gson, Object object) {
      json = gson.toJson(object);
    }

    @Override public MimeType mimeType() {
      return MimeType.JSON;
    }

    @Override public int length() {
      return json.length();
    }

    @Override public void writeTo(OutputStream out) throws IOException {
      out.write(json.getBytes("UTF-8")); // TODO use actual encoding
    }
  }
}

@@ -124,69 +124,8 @@
 on;%0A
-import retrofit.io.MimeType;%0Aimport retrofit.io.TypedBytes;%0A%0A
 impo
@@ -264,25 +264,130 @@
 ava.
-lang.reflect.Type
+io.UnsupportedEncodingException;%0Aimport java.lang.reflect.Type;%0Aimport retrofit.io.MimeType;%0Aimport retrofit.io.TypedBytes
 ;%0A%0A/
@@ -578,16 +578,93 @@
 erter %7B%0A
+  public static final String ENCODING = %22UTF-8%22; // TODO use actual encoding%0A
   privat
@@ -842,42 +842,8 @@
 y %7B%0A
-      // TODO use actual encoding%0A
     
@@ -922,23 +922,24 @@
 (body), 
-%22UTF-8%22
+ENCODING
 );%0A     
@@ -1316,19 +1316,24 @@
 nal 
-String json
+byte%5B%5D jsonBytes
 ;%0A%0A 
@@ -1388,35 +1388,205 @@
     
-json = gson.toJson(object);
+try %7B%0A        jsonBytes = gson.toJson(object).getBytes(ENCODING);%0A      %7D catch (UnsupportedEncodingException e) %7B%0A        throw new IllegalArgumentException(ENCODING + %22 doesn't exist!?%22);%0A      %7D
 %0A   
@@ -1724,17 +1724,20 @@
 json
+Bytes
 .length
-()
 ;%0A  
@@ -1838,56 +1838,15 @@
 json
-.get
 Bytes
-(%22UTF-8%22)); // TODO use actual encoding
+);
 %0A   

Use proper byte length for multibyte strings