Retrofit2 POST主体作为原始JSON

IrApp

我正在尝试使用Microsoft Translator API翻译一些文本我正在使用Retrofit 2这是代码:

 public RestClient() {
    final OkHttpClient httpClient = new OkHttpClient.Builder()
            .addNetworkInterceptor(new Interceptor() {
                @Override
                public Response intercept(Chain chain) throws IOException {
                    final Request originalRequest = chain.request();
                    Request newRequest;

                    newRequest = originalRequest.newBuilder()
                            .header("Content-Type", "application/json")
                            .header("Ocp-Apim-Subscription-Key", "KEY")
                            .header("X-ClientTraceId", java.util.UUID.randomUUID().toString())
                            .build();
                    return chain.proceed(newRequest);
                }
            })
            .addNetworkInterceptor(new HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY))
            .build();


    // Build the retrofit config from our http client
    final Retrofit retrofit = new Retrofit.Builder()
            .baseUrl("https://api.cognitive.microsofttranslator.com/")
            .client(httpClient)
            .addConverterFactory(GsonConverterFactory.create())
            .build();

    // Build api instance from retrofit config
    api = retrofit.create(RestApi.class);
}


public interface RestApi {

    @POST("translate?api-version=3.0&from=en&to=zh-Latn")
    Call<TranslationResultDTO> getTranslation(@Body final RequestBody Text);
}


 public void getTranslation(final String text, final RestCallback<TranslationResultDTO> translationResultCallback) {
    final JsonObject jsonBody = new JsonObject();
    jsonBody.addProperty("Text", text);
    RequestBody textToTranslateBody = RequestBody.create(MediaType.parse("application/json"), jsonBody.toString());

    Call<TranslationResultDTO> call = api.getTranslation(textToTranslateBody);

    call.enqueue(new Callback<TranslationResultDTO>() {
        @Override
        public void onResponse(Call<TranslationResultDTO> call, retrofit2.Response<TranslationResultDTO> response) {
            final int responseCode = response.code();
            ....
        }

        @Override
        public void onFailure(Call<TranslationResultDTO> call, Throwable t) {
            ....
        }
    });
}

我从服务器收到错误消息。该错误表明该机体无效JSON

有人知道问题出在哪里吗?提前致谢!

更新

这是我也尝试过的另一种解决方案的代码。此解决方案使用POJO类:

public class Data {

@SerializedName("Text")
private String text;

public Data(String text) {
    this.text = text;
}

public String getText() {
    return text;
}

public void setText(String text) {
    this.text = text;
}

}

@POST("translate?api-version=3.0&from=en&to=zh-Latn")
Call<TranslationResultDTO> getTranslation(@Body final Data Text);


 Data data = new Data("text value to translate");
    Call<TranslationResultDTO> call = api.getTranslation(data);

同样是错误的:/

沙珊斯

该错误表明正文中没有有效的JSON。

这是服务器的预期响应。假设以下是您要发送的JSON正文,

{
    "key_1" : "value 1",
    "key_2" : "value 2",
}

当您使用时JsonObject#toString(),它会变成这样

{\"key_1\" : \"value 1\", \"key_2\" : \"value 2\"}

如果您将上述JSON数据/正文发送到服务器,则服务器会将其视为普通String。

仍然需要在toString()这里使用,因为MediaType#parse()它不接受JsonObject参数。

有什么解决方案?

正如Ishan Fernando在他的评论中提到的那样,您需要创建一个自定义POJO类来为请求准备JSON主体。或用于HashMap准备身体。

如下创建POJO

import com.google.gson.annotations.SerializedName;

public class Data {

    @SerializedName("Text")
    private String text;

    public Data(String text) {
        this.text = text;
    }

    // getter and setter methods
}

并使用它

Data data = new Data("text value to translate"); // construct object
Call<TranslationResultDTO> call = api.getTranslation(data); // change method parameter

并在API界面中调整方法参数

Call<TranslationResultDTO> getTranslation(@Body final Data text); // change method parameter

编辑1

我仔细阅读了您的问题所附的文档。我犯了一个小错误。JSON正文应包含JSONArray,而不是JSONObject。像下面

[
    {
        "Text" : "text to translate"
    }
]

List<Data>在API界面中将method参数更改为

Call<TranslationResultDTO> getTranslation(@Body final List<Data> text); // change method parameter

如下使用

Data data = new Data("text value to translate"); // construct object
List<Data> objList = new ArrayList<>();
objList.add(data);
Call<TranslationResultDTO> call = api.getTranslation(objList);  // change method parameter

编辑2

API也将使用JSONArray进行响应。样品回复

[
    {
        "detectedLanguage": {
        "language": "en",
        "score": 1.0
        },
        "translations": [
        {
            "text": "Hallo Welt!",
            "to": "de"
        },
        {
            "text": "Salve, mondo!",
            "to": "it"
            }
        ]
    }
]

创建以下POJO类以正确解析JSON响应

Translation.java

import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

public class Translation {

    @SerializedName("text")
    @Expose
    private String text;
    @SerializedName("to")
    @Expose
    private String to;

    // constructors, getter and setter methods

}

DetectedLanguage.java

import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

public class DetectedLanguage {

    @SerializedName("language")
    @Expose
    private String language;
    @SerializedName("score")
    @Expose
    private float score;

    // constructors, getter and setter methods

}

最后,调整如下的TranslationResultDTO.java类。

import java.util.List;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

public class TranslationResultDTO {

    @SerializedName("detectedLanguage")
    @Expose
    private DetectedLanguage detectedLanguage;
    @SerializedName("translations")
    @Expose
    private List<Translation> translations = null;

    // constructors, getter and setter methods

}

接口类

Call<List<TranslationResultDTO>> call = api.getTranslation(objList);    // change method parameter

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章