2017-09-24 88 views
-5

我在我的项目中使用retrofit 2。在项目中,我应该张贴数据到服务器像波纹管:如何将带格式“json”的数据发送到服务器进行改造2? - Android

{ 
    "query":"XXXXXX", 
    "variables": { 
    "vendorId":10, 
    "orderId":10, 
    "shippingMethod":33, 
    "trackingCode": "124", 
    "shippingDate": "2017-09-24", 
    "shippingCost": 10000, 
    "description": "", 
    } 
} 

如何我格式json将数据发送到服务器?

+2

你是什么具体问题?你尝试过Gson吗? – barotia

+0

https://futurestud.io/tutorials/retrofit-send-objects-in-request-body – FarshidABZ

+0

[如何在Retrofit请求的主体中发布原始整个JSON?](https://stackoverflow.com /问题/ 21398598 /如何对后期原料 - 全JSON-内式车身的-A-改装的要求) –

回答

-1

我想如果你要为你的JSON创建一个POJO类并使用@Body body发布它,它应该可以工作。

因为,Retrofit 2将使用选择的转换器库来处理来自Java对象的数据的反序列化。如果使用@Body参数为参数注释,则此工作将自动完成。例如,如果您正在使用Gson库,则将为您序列化属于该类的任何字段。您可以使用@SerializedName装饰器更改此名称。

此链接将帮助您更多。 Converting JSON to POJO and posting it

请不要纠正我,如果这不是你正在寻找。

感谢

-2

为您的JSON一类,然后创建一个对象,然后使用@Body

0

创建这样一个JSON对象,它张贴,

JSONObject rootObject=new JSONObject(); 
    JSONObject variablesObj=new JSONObject(); 
    try { 
     rootObject.put("query","XXXXX"); 
     variablesObj.put("vendorId","10"); 
     variablesObj.put("orderId","10"); 
     variablesObj.put("shippingMethod","33"); 
     variablesObj.put("trackingCode","124"); 
     variablesObj.put("shippingDate","2017-09-24"); 
     variablesObj.put("shippingCost","10000"); 
     variablesObj.put("description",""); 
     rootObject.put("variables",variablesObj); 
    } catch (JSONException e) { 
     e.printStackTrace(); 
    } 

通这一样的界面,

YourRetrofitInterface request = 
retrofit.create(YourRetrofitInterface.class); 
    Call<yourModel> call1=request.getData(rootObject); 

现在发布在YourRetrofitInterface的主体中

@Headers("Content-Type: application/json") 
@POST("yourEndpoint.php") 
Call<yourModel> getData(@Body JSONObject jsonObject); 

FYI:使用yourModel(POJO),让您回应

相关问题