如何在改造android中发布数组

时间:2016-05-16 12:45:16

标签: android retrofit

如何通过post方法在改造中发布以下参数?

 "params":{"body": {
    "learning_objective_uuids": [
      "ED4FE2BB2008FDA9C8133FF462959C0968FAB98C4D1DB8F2"
    ],
    "note": "FasfAFSASFASDF",
    "user_uuids": [
      "EDF8B7EC20005ACC5C40FF7D6E988801F5BAD83CBBCDB97F",
      "EDF8F78F2000569C64101F244AA20C0070D2A7FCB1939E19"
    ]
  }
}
} }

7 个答案:

答案 0 :(得分:37)

@FormUrlEncoded
@POST("service_name") 
   void functionName(
        @FieldMap Map<String, String> learning_objective_uuids, @FieldMap Map<String, String> user_uuids, @Field("note") String note,
        Callback<CallBackClass> callback
    );

更好的解决方案:使用arraylist ..参考链接:johnsonsu

@FormUrlEncoded
    @POST("service_name") 
       void functionName(
            @Field("learning_objective_uuids[]") ArrayList<String> learning_objective_uuids, @Field("user_uuids[]") ArrayList<String> user_uuids, @Field("note") String note,
            Callback<CallBackClass> callback
        );

答案 1 :(得分:5)

请参阅此示例,其中我需要将注册字段数据作为json请求传递

@POST("magento2apidemo/rest/V1/customers")
Call<RegisterEntity> customerRegistration(@Body JsonObject registrationData);

这里我创建了registrationData是

private static JsonObject generateRegistrationRequest() {
        JSONObject jsonObject = new JSONObject();
        try {
            JSONObject subJsonObject = new JSONObject();
            subJsonObject.put("email", "abc@xyz.com");
            subJsonObject.put("firstname", "abc");
            subJsonObject.put("lastname", "xyz");

            jsonObject.put("customer", subJsonObject);
            jsonObject.put("password", "password");

        } catch (JSONException e) {
            e.printStackTrace();
        }
        JsonParser jsonParser = new JsonParser();
        JsonObject gsonObject = (JsonObject) jsonParser.parse(jsonObject.toString());
        return gsonObject;
    }

答案 2 :(得分:1)

访问此网站:JSON Schema 2 POJO

粘贴您的示例Json格式,然后

选择源类型:JSON,注释样式:无

然后创建一个POJO类,例如你的类名:MyPOJOClass

然后在你的Api中:

@POST("endpoint")
public Call<Void> postArray(@Body MyPOJOClass mypojoclass);

如果您也有标题,可以将它们添加到以下参数中:

@Header("Accept") String accept,@Header("Content-Type") String contentType

@Edit:对于您的评论结帐我的回答:how-to-use-gson-2-0-on-onresponse-from-retrofit-2-0

答案 3 :(得分:0)

如果您要发送同名列表,则在retrofit2中对我有用的唯一方法是使用import Foundation import CoreData class Product: NSManagedObject, Encodable, Decodable { @NSManaged var mongoID:[String:String] @NSManaged var title:String @NSManaged var productID:Int @NSManaged var mpn:String @NSManaged var listPrice:Float @NSManaged var price:Float @NSManaged var uom:String @NSManaged var uomQty:Int @NSManaged var inventory:Float @NSManaged var minSaleQty:Int @NSManaged var desc:String @NSManaged var categories:[String] @NSManaged var imageURL:String @NSManaged var upc:String @NSManaged var quantity:Int @NSManaged var disc:Bool enum CodingKeys: String, CodingKey { case mongoID = "mongoID" case title = "title" case productID = "productID" case mpn = "mpn" case listPrice = "listPrice" case price = "price" case uom = "uom" case uomQty = "uomQty" case inventory = "inventory" case minSaleQty = "minSaleQty" case desc = "desc" case categories = "categories" case imageURL = "imageURL" case upc = "upc" case quantity = "quantity" case disc = "disc" } required convenience init(from decoder:Decoder) throws { guard let context = decoder.userInfo[CodingUserInfoKey.context!] as? NSManagedObjectContext else { print("failed context get"); return } guard let entity = NSEntityDescription.entity(forEntityName: "Product", in: context) else { print("failed entity init"); return } self.init(entity: entity, insertInto: context) let container = try decoder.container(keyedBy: CodingKeys.self) self.mongoID = try container.decodeIfPresent([String:String].self, forKey: .mongoID) ?? ["$id":"nil"] self.title = try container.decodeIfPresent(String.self, forKey: .title) ?? "" self.productID = try container.decodeIfPresent(Int.self, forKey: .productID) ?? 0 self.mpn = try container.decodeIfPresent(String.self, forKey: .mpn) ?? "" self.listPrice = try container.decodeIfPresent(Float.self, forKey: .listPrice) ?? 0.0 self.price = try container.decodeIfPresent(Float.self, forKey: .price) ?? 0.0 self.uom = try container.decodeIfPresent(String.self, forKey: .uom) ?? "" self.uomQty = try container.decodeIfPresent(Int.self, forKey: .uomQty) ?? 0 self.inventory = try container.decodeIfPresent(Float.self, forKey: .inventory) ?? 0.0 self.minSaleQty = try container.decodeIfPresent(Int.self, forKey: .minSaleQty) ?? 0 self.desc = try container.decodeIfPresent(String.self, forKey: .desc) ?? "" self.categories = try container.decodeIfPresent([String].self, forKey: .categories) ?? [""] self.imageURL = try container.decodeIfPresent(String.self, forKey: .imageURL) ?? "" self.upc = try container.decodeIfPresent(String.self, forKey: .upc) ?? "" self.quantity = try container.decodeIfPresent(Int.self, forKey: .quantity) ?? 0 self.disc = try container.decodeIfPresent(Bool.self, forKey: .disc) ?? false }//'self.init' isn't called on all paths before returning from initializer public func encode(to encoder: Encoder) throws { } } extension CodingUserInfoKey { static let context = CodingUserInfoKey(rawValue: "context") }

@Query

这将发送为:@FormUrlEncoded @POST("service_name") void functionName( @Query("category") List<Int> categories );

公认的答案似乎在Retrofit2中不起作用

答案 4 :(得分:0)

从今天开始,运行改造implementation 'com.squareup.retrofit2:retrofit:2.1.0'

这很好用...

@FormUrlEncoded
@POST("index.php?action=item")
Call<Reply> updateManyItem(@Header("Authorization") String auth_token, @Field("items[]") List<Integer> items, @Field("method") String method);

您可以忽略@Header@Field("method")...。主要部分是@Field("items[]") List<Integer> items

这是允许您发送项目的内容。在API方面,我只是在寻找整数数组,因此效果很好。

答案 5 :(得分:0)

我找到了一个新的解决方法:

您可以将其作为字符串发送:

@POST("CollectionPoints")
@FormUrlEncoded
Call<SomeResponse> postSomething(@Field("ids")String ids);

并通过以下方式发送通过:

Call<SomeResponse> call = service.postSomething("0","0", Arrays.toString(new int[]{53551, 53554}));

最好的问候!

答案 6 :(得分:0)

Gson是解决JSON对象/数组相关问题的最佳解决方案。

在这里,我正在分享我最简单的解决方案,以在改造API中传递数组类型值

id: ArrayList<String> //Already initilized 
status: String  //Already initilized 

val jsonObject = JsonObject()
val toJson = Gson().toJsonTree(id) //Only one line to covert array JsonElement

jsonObject.add("id", toJson) //Add Json Element in JsonObject

jsonObject.addProperty("status", status)
使用 jsonObject

API调用

@POST("API_END_POINT")
fun changeStatusOfList(@Body jsonObject: JsonObject): Observable<Response<RETURN_TYPE>>

日志输出:

{"id":["426","427"],"status":"1"}