Android 如何将包含JSON对象数据的JSON数组发布到服务器?
我想将下面的JSON数据发送到服务器,并在android和服务器中读取响应。下面是Json数据 x和y是图像的坐标Android 如何将包含JSON对象数据的JSON数组发布到服务器?,android,json,web-services,android-asynctask,Android,Json,Web Services,Android Asynctask,我想将下面的JSON数据发送到服务器,并在android和服务器中读取响应。下面是Json数据 x和y是图像的坐标 lstCoordinate:[ { x=xValue y=yValue img_id=image } { x=xVal
lstCoordinate:[
{
x=xValue
y=yValue
img_id=image
}
{
x=xValue
y=yValue
img_id=image
}
]
建议创建一个具体的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);
你试了什么?也发布你的来源。参考这个答案,这可能会对你有所帮助。我第一次尝试,这就是为什么我问@vicjordan抱歉,我不想使用改装服务。我只是在使用Tomcat Server@JayThummarThis来处理一个特定的案例。在现实世界中,更好的形式是创建自己的POJO类
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();