【问题标题】:how to post JSON ARRAY with JSON OBJECT data to server?如何将带有 JSON OBJECT 数据的 JSON ARRAY 发布到服务器?
【发布时间】:2018-11-12 07:15:43
【问题描述】:

我想将以下 JSON 数据发送到服务器并读取 android 和服务器中的响应。下面是 Json 数据。

x 和 y 是图像的坐标。

lstCoordinate:[
                   {
                   x=xValue
                   y=yValue
                   img_id=image
                   }
                   {
                   x=xValue
                   y=yValue
                   img_id=image
                   }
              ]

【问题讨论】:

标签: android json web-services android-asynctask


【解决方案1】:

建议是创建一个具体的 Java 对象来表示您的应用程序中的数据。您也必须(推荐)使用库作为 okHttp 或改造来处理应用程序中的请求,因为随着应用程序的增长,将使用对象更有条理,而不是直接使用 json。

示例:
具体类

  public class Coordinate {
        private String X;
        private String Y;
        private int ImageID;

        public Coordinate(String X, String Y, int ImageID) {
            this.X = X;
            this.Y = Y;
            this.ImageID = ImageID;
        }
        public String GetX() {
            return this.X;
        }
        public String GetY() {
            return this.Y;
        }
        public int GetImageID() {
            return this.ImageID;
        }
        public void SetX(String X) {
            this.X = X;
        }
        public void SetY(String Y) {
            this.Y = Y;
        }
        public void GetImageID(int ImageID) {
            this.ImageID = ImageID;
        }
    }

转化

 Gson gson = new Gson();

    List<Coordinate> coordinates = new ArrayList<>();

    coordinates.add(new Coordinate("-300511237", "-512133938", 1));
    coordinates.add(new Coordinate("28614723", "77210005", 2));

    String json = gson.toJson(coordinates);

使用 okHttp 请求

public static final MediaType JSON
    = MediaType.parse("application/json; charset=utf-8");

OkHttpClient client = new OkHttpClient();

String post(String url, String json) throws IOException {
  RequestBody body = RequestBody.create(JSON, json);
  Request request = new Request.Builder()
      .url(url)
      .post(body)
      .build();
  Response response = client.newCall(request).execute();
  return response.body().string();

【讨论】:

  • 这将适用于特定情况。在现实世界中,更好的形式是制作自己的 POJO 类。
  • 感谢先生,我将尝试在我的代码中实现
猜你喜欢
  • 2014-04-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-05-22
相关资源
最近更新 更多