我需要向我的Web服务发送一个json,json是:
{
"Sala": {
"usuario": "%@",
"adversario": "%@",
"atualizacao": "%@",
"device": "%@",
"device_tipo": "ios"
}
}
.我正在尝试使用API 1.8进行改装。当我尝试发送帖子时,会抛出一个异常。
例外情况:
com.google.gson.JsonSyntaxException: com.google.gson.stream.MalformedJsonException: Use JsonReader.setLenient(true) to accept malformed JSON at line 1 column 7 path $
我在试这个
public class ChatObject {
private String usuario;
private String adversario;
private String atualizacao;
private String email;
private String device;
private String device_tipo;
改装接口
@POST("/WsChat/interacao.json")
public void onReceiveMessage(@Body ChatObject obj,
Callback<JsonElement> response);
工具
public void receiveMessage(){
///{\"Sala\":{\"usuario\":\"%@\",\"adversario\":\"%@\",\"atualizacao\":\"%@\",\"device\":\"%@\",\"device_tipo\":\"ios\"}}
ChatObject chatObject = new ChatObject(BatalhaConfigs.USUARIO_EMAIL,
BatalhaConfigs.ADVERSARIO_EMAIL,
new Date().toString(),
BatalhaConfigs.USUARIO_EMAIL,
AndroidReturnId.getAndroidId(),
"android");
RestAdapter adapter = new RestAdapter.Builder()
.setLogLevel(RestAdapter.LogLevel.FULL)
.setRequestInterceptor(new CustomRequestInterceptor())
.setEndpoint(END_POINT)
.build();
ChatListener listener = adapter.create(ChatListener.class);
listener.onReceiveMessage(chatObject, new Callback<JsonElement>() {
@Override
public void success(JsonElement jsonElement, retrofit.client.Response response) {
Log.i("JSON ELEMENT->", jsonElement.toString());
}
@Override
public void failure(RetrofitError error) {
Log.i("FALHOU->", error.getLocalizedMessage());
}
});
}
RestAdapter adapterRfqPost = new RestAdapter.Builder()
.setEndpoint(Constants.ENDPOINT)
`enter code here`.setConverter(new ConstantsMethods.StringConverter())
.build();
public static class StringConverter implements Converter {
@Override
public Object fromBody(TypedInput typedInput, Type type) throws ConversionException {
String text = null;
try {
text = fromStream(typedInput.in());
} catch (IOException ignored) {/*NOP*/ }
return text;
}
@Override
public TypedOutput toBody(Object o) {
return null;
}
public static String fromStream(InputStream in) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuilder out = new StringBuilder();
String newLine = System.getProperty("line.separator");
String line;
while ((line = reader.readLine()) != null) {
out.append(line);
out.append(newLine);
}
return out.toString();
}
}
似乎它在改型2.0后略有变化
我是这样做的:
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("http://whatever.com")
.addConverterFactory(LenientGsonConverterFactory.create(gson))
.build();
新的宽大gson工厂:
public final class LenientGsonConverterFactory extends Converter.Factory {
/**
* Create an instance using a default {@link Gson} instance for conversion. Encoding to JSON and
* decoding from JSON (when no charset is specified by a header) will use UTF-8.
*/
public static LenientGsonConverterFactory create() {
return create(new Gson());
}
/**
* Create an instance using {@code gson} for conversion. Encoding to JSON and
* decoding from JSON (when no charset is specified by a header) will use UTF-8.
*/
public static LenientGsonConverterFactory create(Gson gson) {
return new LenientGsonConverterFactory(gson);
}
private final Gson gson;
private LenientGsonConverterFactory(Gson gson) {
if (gson == null) throw new NullPointerException("gson == null");
this.gson = gson;
}
@Override
public Converter<ResponseBody, ?> responseBodyConverter(Type type, Annotation[] annotations,
Retrofit retrofit) {
TypeAdapter<?> adapter = gson.getAdapter(TypeToken.get(type));
return new LenientGsonResponseBodyConverter<>(gson, adapter);
}
@Override
public Converter<?, RequestBody> requestBodyConverter(Type type,
Annotation[] parameterAnnotations, Annotation[] methodAnnotations, Retrofit retrofit) {
TypeAdapter<?> adapter = gson.getAdapter(TypeToken.get(type));
return new LenientGsonRequestBodyConverter<>(gson, adapter);
}
}
宽大的响应解析:
private class LenientGsonResponseBodyConverter<T> implements Converter<ResponseBody, T> {
private final Gson gson;
private final TypeAdapter<T> adapter;
LenientGsonResponseBodyConverter(Gson gson, TypeAdapter<T> adapter) {
this.gson = gson;
this.adapter = adapter;
}
@Override
public T convert(ResponseBody value) throws IOException {
JsonReader jsonReader = gson.newJsonReader(value.charStream());
jsonReader.setLenient(true);
try {
return adapter.read(jsonReader);
} finally {
value.close();
}
}
}
宽大的请求创建:
private class LenientGsonRequestBodyConverter<T> implements Converter<T, RequestBody> {
private static final MediaType MEDIA_TYPE = MediaType.parse("application/json; charset=UTF-8");
private static final Charset UTF_8 = Charset.forName("UTF-8");
private final Gson gson;
private final TypeAdapter<T> adapter;
LenientGsonRequestBodyConverter(Gson gson, TypeAdapter<T> adapter) {
this.gson = gson;
this.adapter = adapter;
}
@Override
public RequestBody convert(T value) throws IOException {
Buffer buffer = new Buffer();
Writer writer = new OutputStreamWriter(buffer.outputStream(), UTF_8);
JsonWriter jsonWriter = gson.newJsonWriter(writer);
jsonWriter.setLenient(true);
adapter.write(jsonWriter, value);
jsonWriter.close();
return RequestBody.create(MEDIA_TYPE, buffer.readByteString());
}
}
我只是复制了改造源代码,并向请求和响应转换器添加了一行jsonWriter.setLenient(true);
甚至更简单:
Gson gson = new GsonBuilder()
.setLenient()
.create();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("http://whatever.com")
.addConverterFactory(GsonConverterFactory.create(gson))
.build();
com.google.格森。JsonSyntaxException:com.google.格森。流动格式错误的JSONException:使用JsonReader。setLenient(true)
通常在存在使JSON变形的字符时抛出。异常消息本身建议使反序列化更加宽容。
但是我建议你修复你的JSON,并从不需要的字符中删除它。
您应该扩展GsonConzer
并覆盖from mBody()
,使Gson
从宽容的JsonReader
中读取。然后将其设置为你的RestAdapter
。这将尝试使用容忍的JsonReader
反序列化,然后关闭它,如果没有引发异常。
public class LenientGsonConverter extends GsonConverter {
private Gson mGson;
public LenientGsonConverter(Gson gson) {
super(gson);
mGson = gson;
}
public LenientGsonConverter(Gson gson, String charset) {
super(gson, charset);
mGson = gson;
}
@Override
public Object fromBody(TypedInput body, Type type) throws ConversionException {
boolean willCloseStream = false; // try to close the stream, if there is no exception thrown using tolerant JsonReader
try {
JsonReader jsonReader = new JsonReader(new InputStreamReader(body.in()));
jsonReader.setLenient(true);
Object o = mGson.fromJson(jsonReader,type);
willCloseStream = true;
return o;
} catch (IOException e) {
e.printStackTrace();
}finally {
if(willCloseStream) {
closeStream(body);
}
}
return super.fromBody(body, type);
}
private void closeStream(TypedInput body){
try {
InputStream in = body.in();
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
我有一个web api和一个应用程序。所以我想注册一个应用程序,但我有一个问题。我使用azure。这是我的registerapi(接口) 还有我的主要活动。java页面 我没有得到改造404没有找到。
我有以下设置: 我正在尝试处理服务器关闭,用户出现连接超时异常的情况,这是我的日志记录: 完整日志记录:http://pastebin.com/gscCGb7x 有没有办法将其转化为改造失败的方法,这样我就可以在那里处理它? 提前感谢!
我有一个场景,我必须调用具有相同基本URL的API,例如,但具有不同的。 我有一个Retrofit 2的实例,它是通过构建的: 如下所示: 对于某些,我必须调用相同的API,但在其他情况下,我必须从完全不同的调用它。如何更改实例以因此在运行时指向不同的URL? 改装实例没有
我知道有几个类似的问题,但没有一个与我的问题相符。我有来自服务器的JSON响应,如下所示: 我的模型课是这样的: DataBeacon有信标和网桥对象列表: } 下面是我获取json的界面: 在我看来,一切都应该正常工作,但我仍然遇到了异常:。我不知道为什么——模型的结构应该是正确的。
重头戏来了,打开conf/ioc/dao.js, 修改dao的定义 dao : { type : "org.nutz.dao.impl.NutDao", args : [{refer:"dataSource"}], fields : { interceptors : [{ref
打开WebContent/WEB-INF/jsp/user/profile.jsp, 在这段代码后面 邮箱验证状态:<c:out value="${obj.emailChecked}"></c:out><p /> 加入 <c:if test="${!obj.emailChecked}"> <script type="text