gpt4 book ai didi

java - 如何在 Android 中解析换行符分隔的 Json 响应?

转载 作者:太空狗 更新时间:2023-10-29 16:33:48 28 4
gpt4 key购买 nike

样本 NdJson数据:

{"type":"data","id":"xyz"}
{"type":"value","id":"xcf"}
....
....

这是我的 RetrofitRxJava使用 limit=1 获取数据时工作正常的代码即 {"type":"data","id":"xyz"} .

 adapter.create(API.class).getData()
.subscribeOn(Schedulers.newThread())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Observer<APIData>() {
@Override
public void onCompleted() {}

@Override
public void onError(Throwable e) {}

@Override
public void onNext(APIData apidata) {}

});

我的模型类

模型类只有两个参数:

public class APIData(){
private String type;
private String id;

..// Getter and setter for above two fields
}

API类

public interface WarehouseAPI {
@GET("/search?limit=1")
public Observable<APIData> getdata ();
}

我在替换 @GET("/search?limit=1") 时遇到的错误与 @GET("/search")Malformed JSON: Syntax error .

问题

如何正确解析 NdJson

有什么方法可以将响应存储在 List<APIData> 中吗?

编辑-1

现在我正在尝试接受通用 Response在观察者中:

adapter.create(APIData.class).getdata()
.subscribeOn(Schedulers.newThread())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Observer<Response>() {
@Override
public void onCompleted() {}

@Override
public void onNext(Response response) {}
});

但是得到 no suitable method found for subscribe(<anonymous Observer<Response>>)

编辑-2

但是,我犯了一些愚蠢的错误,我在“Edit-1”部分遇到的错误现在已修复。现在我得到了

Error:retrofit.RetrofitError: com.google.gson.JsonSyntaxException: com.google.gson.stream.MalformedJsonException: Use JsonReader.setLenient(true) to accept malformed JSON at line 2 column 2 path $

最佳答案

为了让事情正常进行,我必须添加 Custom converterRetrofit.Converter 实现:

public class CustomConverter implements Converter {

@Override
public Object fromBody(TypedInput body, Type type) throws ConversionException {
String text = null;
try {
text = fromStream(body.in());
} catch (IOException e) {
e.printStackTrace();
}
return text;

}

@Override
public TypedOutput toBody(Object object) {
return null;
}

// Custom method to convert stream from request to string
public static String fromStream(InputStream in) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuilder out = new StringBuilder();
String newLine = System.getProperty("\n");
String line;
while ((line = reader.readLine()) != null) {
out.append(line);
out.append(newLine);
}
return out.toString();
}
}

而且效果很好!

关于java - 如何在 Android 中解析换行符分隔的 Json 响应?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33201851/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com