问题描述
我在想,我怎么可能去使用改造发送自定义对象到我的API,这样的事情:
I was wondering how could I go about sending a custom object to my API using retrofit, something like this:
@POST(URL_ORDERS)
public void newOrder(Order order, Callback<Boolean> success);
下面就是我会分析它在我的服务器
Here's how I'd parse it on my server
public function store()
{
if(Auth::check()){
$order = Input::get();
$table = $order->table;
$items = $order->items;
if(!$table->taken){
$table->taken = true;
$order->push();
$table->push();
return true;
}
}
return false;
}
出于某种原因,我得到
For some reason I'm getting
06-04 20:45:59.275 6085-6306/com.tesis.restapp.restapp W/dalvikvm﹕ threadid=11: thread exiting with uncaught exception (group=0x40aae210)
06-04 20:45:59.285 6085-6306/com.tesis.restapp.restapp E/AndroidRuntime﹕ FATAL EXCEPTION: Retrofit-Idle
java.lang.IllegalArgumentException: RestAppApiInterface.newOrder: No Retrofit annotation found. (parameter #1)
at retrofit.RestMethodInfo.methodError(RestMethodInfo.java:120)
at retrofit.RestMethodInfo.parameterError(RestMethodInfo.java:124)
at retrofit.RestMethodInfo.parseParameters(RestMethodInfo.java:443)
at retrofit.RestMethodInfo.init(RestMethodInfo.java:131)
我猜我希望它做的就是以某种方式改变我的对象为JSON并将其发送到我的服务器。我在这接近正确的方式?
I guess what I want it do to is to somehow transform my object into a json and send it to my server. Am I approaching this the right way?
推荐答案
该错误是不提供有关你的订购
参数。将其更改为: @Body
注释
The error is from not providing the @Body
annotation on your Order
parameter. Change it to:
@POST(URL_ORDERS)
public void newOrder(@Body Order order, Callback<Boolean> success);
改造使用序列化和默认反序列化JSON。 GSON默认情况下,序列化使用的变量名,但他们可以使用注释来改变 @SerializedName(replacement_name)
。
Retrofit uses Gson to serialize and deserialize JSON by default. Gson uses variable names by default for serialization, but they can be changed using the annotation @SerializedName("replacement_name")
.
例如,如果你的订单
类是这样的:
For Example, If your Order
class looked like this:
public class Order {
@SerializedName("custom_id")
private int id;
private String name;
private List<Item> items;
}
public class Item {
private int id;
private String name;
}
然后GSON将自动序列化到
Then Gson would automatically serialize that to
{
"custom_id": 1,
"name": "Hello Object",
"items": [
{
"id": 1,
"name": "Hello Item"
}
]
}
这篇关于Android的改造|邮政自定义对象(JSON发送到服务器)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!