Android如何通过Retrofit提交Json格式数据

本文将介绍如何通过retrofit库post一串json格式的数据。首先post的json数据格式如下:

{
 "Id": "string",
 "DeviceId": "string",
 "Name": "string",
 "SumDistance": 0,
 "RouteNo": "string",
 "SumPoints": 0,
 "SetupTime": "2016-06-10T13:11:00.766Z",
 "UsedTime": 0,
 "Points": [
  {
   "Id": "string",
   "RouteNo": "string",
   "Name": "string",
   "Longitude": "string",
   "Latitude": "string",
   "Height": 0,
   "Distance": 0,
   "Yaw": 0,
   "Pitch": 0,
   "Speed": 0,
   "Usedtime": 0
  }
 ]
}

通过安装Android studio gsonformat插件,根据上面的json格式自动生成一个Bean类,本文命名为FlyRouteBean,

package com.example.administrator.retrofitex;
import java.util.List; 

import android.os.Parcel;
import android.os.Parcelable; 

/**
 * Created by Administrator on 2016/6/10.
 */
public class FlyRouteBean{ 

  /**
   * Id : string
   * DeviceId : string
   * Name : string
   * SumDistance : 0
   * RouteNo : string
   * SumPoints : 0
   * SetupTime : 2016-05-23T06:20:50.254Z
   * UsedTime : 0
   * Points : [{"Id":"string","RouteNo":"string","Name":"string","Longitude":"string","Latitude":"string","Height":0,"Distance":0,"Yaw":0,"Pitch":0,"Speed":0,"Usedtime":0}]
   */ 

  public String Id;
  public String DeviceId;
  public String Name;
  public double SumDistance;
  public String RouteNo;
  public int SumPoints;
  public String SetupTime;
  public double UsedTime;
  /**
   * Id : string
   * RouteNo : string
   * Name : string
   * Longitude : string
   * Latitude : string
   * Height : 0
   * Distance : 0
   * Yaw : 0
   * Pitch : 0
   * Speed : 0
   * Usedtime : 0
   */ 

  public List<PointsBean> Points; 

  public String getId() {
    return Id;
  } 

  public void setId(String Id) {
    this.Id = Id;
  } 

  public String getDeviceId() {
    return DeviceId;
  } 

  public void setDeviceId(String DeviceId) {
    this.DeviceId = DeviceId;
  } 

  public String getName() {
    return Name;
  } 

  public void setName(String Name) {
    this.Name = Name;
  } 

  public double getSumDistance() {
    return SumDistance;
  } 

  public void setSumDistance(double SumDistance) {
    this.SumDistance = SumDistance;
  } 

  public String getRouteNo() {
    return RouteNo;
  } 

  public void setRouteNo(String RouteNo) {
    this.RouteNo = RouteNo;
  } 

  public int getSumPoints() {
    return SumPoints;
  } 

  public void setSumPoints(int SumPoints) {
    this.SumPoints = SumPoints;
  } 

  public String getSetupTime() {
    return SetupTime;
  } 

  public void setSetupTime(String SetupTime) {
    this.SetupTime = SetupTime;
  } 

  public double getUsedTime() {
    return UsedTime;
  } 

  public void setUsedTime(double UsedTime) {
    this.UsedTime = UsedTime;
  } 

  public List<PointsBean> getPoints() {
    return Points;
  } 

  public void setPoints(List<PointsBean> Points) {
    this.Points = Points;
  } 

  public static class PointsBean implements Parcelable {
    public String Id;
    public String RouteNo;
    public String Name;
    public String Longitude;
    public String Latitude;
    public double Height;
    public double Distance;
    public double Yaw;
    public double Pitch;
    public double Speed;
    public double Usedtime; 

    public String getId() {
      return Id;
    } 

    public void setId(String Id) {
      this.Id = Id;
    } 

    public String getRouteNo() {
      return RouteNo;
    } 

    public void setRouteNo(String RouteNo) {
      this.RouteNo = RouteNo;
    } 

    public String getName() {
      return Name;
    } 

    public void setName(String Name) {
      this.Name = Name;
    } 

    public String getLongitude() {
      return Longitude;
    } 

    public void setLongitude(String Longitude) {
      this.Longitude = Longitude;
    } 

    public String getLatitude() {
      return Latitude;
    } 

    public void setLatitude(String Latitude) {
      this.Latitude = Latitude;
    } 

    public double getHeight() {
      return Height;
    } 

    public void setHeight(double Height) {
      this.Height = Height;
    } 

    public double getDistance() {
      return Distance;
    } 

    public void setDistance(double Distance) {
      this.Distance = Distance;
    } 

    public double getYaw() {
      return Yaw;
    } 

    public void setYaw(double Yaw) {
      this.Yaw = Yaw;
    } 

    public double getPitch() {
      return Pitch;
    } 

    public void setPitch(double Pitch) {
      this.Pitch = Pitch;
    } 

    public double getSpeed() {
      return Speed;
    } 

    public void setSpeed(double Speed) {
      this.Speed = Speed;
    } 

    public double getUsedtime() {
      return Usedtime;
    } 

    public void setUsedtime(double Usedtime) {
      this.Usedtime = Usedtime;
    } 

    @Override
    public String toString() {
      return "PointsBean{" +
          "Id='" + Id + '\'' +
          ", RouteNo='" + RouteNo + '\'' +
          ", Name='" + Name + '\'' +
          ", Longitude='" + Longitude + '\'' +
          ", Latitude='" + Latitude + '\'' +
          ", Height=" + Height +
          ", Distance=" + Distance +
          ", Yaw=" + Yaw +
          ", Pitch=" + Pitch +
          ", Speed=" + Speed +
          ", Usedtime=" + Usedtime +
          '}';
    } 

    @Override
    public void writeToParcel(Parcel dest, int flags) {
      // TODO Auto-generated method stub
      dest.writeString(Id);
      dest.writeString(RouteNo);
      dest.writeString(Name);
      dest.writeString(Longitude);
      dest.writeString(Latitude);
      dest.writeDouble(Height);
      dest.writeDouble(Distance);
      dest.writeDouble(Yaw);
      dest.writeDouble(Pitch);
      dest.writeDouble(Speed);
      dest.writeDouble(Usedtime);
    }
    public static final Creator<PointsBean> CREATOR=new Creator<PointsBean>() { 

      @Override
      public PointsBean createFromParcel(Parcel source) {
        // TODO Auto-generated method stub
        PointsBean pointsBean=new PointsBean();
        pointsBean.setId(source.readString());
        pointsBean.setRouteNo(source.readString());
        pointsBean.setName(source.readString());
        pointsBean.setLongitude(source.readString());
        pointsBean.setLatitude(source.readString());
        pointsBean.setHeight(source.readInt());
        pointsBean.setDistance(source.readInt());
        pointsBean.setYaw(source.readInt());
        pointsBean.setPitch(source.readInt());
        pointsBean.setSpeed(source.readInt());
        pointsBean.setUsedtime(source.readInt());
        return pointsBean;
      } 

      @Override
      public PointsBean[] newArray(int size) {
        // TODO Auto-generated method stub
        return new PointsBean[size];
      } 

    }; 

    @Override
    public int describeContents() {
      // TODO Auto-generated method stub
      return 0;
    }
  } 

  @Override
  public String toString() {
    return "FlyRouteBean{" +
        "Id='" + Id + '\'' +
        ", DeviceId='" + DeviceId + '\'' +
        ", Name='" + Name + '\'' +
        ", SumDistance=" + SumDistance +
        ", RouteNo='" + RouteNo + '\'' +
        ", SumPoints=" + SumPoints +
        ", SetupTime='" + SetupTime + '\'' +
        ", UsedTime=" + UsedTime +
        ", Points=" + Points +
        '}';
  } 

}

然后就来建立接口了,其内容如下:

public interface PostRoute {
  @Headers({"Content-Type: application/json","Accept: application/json"})//需要添加头
  @POST("api/FlyRoute/Add")
  Call<FlyRouteBean> postFlyRoute(@Body RequestBody route);//传入的参数为RequestBody
}

接下来就是提交数据的了:

FlyRouteBean flyRouteBean=new FlyRouteBean();
flyRouteBean=initdata(flyRouteBean);//根据Bean类初始化一个需要提交的数据类
Gson gson=new Gson();
String route= gson.toJson(flyRouteBean);//通过Gson将Bean转化为Json字符串形式 
 Retrofit retrofit=new Retrofit.Builder()
      .baseUrl(URL)
      .addConverterFactory( GsonConverterFactory.create())
      .build();
  PostRoute postRoute=retrofit.create(PostRoute.class);
  RequestBody body=RequestBody.create(okhttp3.MediaType.parse("application/json; charset=utf-8"),route);
  Call<FlyRouteBean> call=postRoute.postFlyRoute(body);
  call.enqueue(new Callback<FlyRouteBean>() {
  @Override
  public void onResponse(Call<FlyRouteBean> call, Response<FlyRouteBean> response) {
    Log.e("sssss","-----------------------"+response.body().getDeviceId());//这里是用于测试,服务器返回的数据就是提交的数据。
  } 

  @Override
  public void onFailure(Call<FlyRouteBean> call, Throwable t) {
    Log.e("sssss",t.getMessage());
  }
});

<----------- 更新如何同时提交json数据和其他查询字段:--------------->

服务器端(ASP):核心代码如下,接收一个json格式学生类,加一个bool类型

 [HttpPost]
  public IHttpActionResult Info(Student stu, bool IsGay)
    {

      return Ok(stu.Name);
    }

客户端:

//接口地址:http://172.20.69.209:9665/api/Test/Info?IsGay={IsGay}
@POST("api/Test/Info")
Call<ResponseBody> postStudent(@Body RequestBody stu,@Query("IsGay") boolean IsGay);

实现代码:

Student stu=new Student();
stu.setId("20103177");
stu.setName("zpm");
stu.setAge(18);
Gson gson=new Gson();
String route= gson.toJson(stu);
Log.e("post", "//");

Retrofit retrofit=new Retrofit.Builder()
    .baseUrl("http://172.20.69.209:9665/")
    .addConverterFactory( GsonConverterFactory.create())
    .build();
PostRoute postRoute=retrofit.create(PostRoute.class);
RequestBody body=RequestBody.create(okhttp3.MediaType.parse("application/json; charset=utf-8"),route);
Call<ResponseBody> call=postRoute.postStudent(body,true);
call.enqueue(new Callback<ResponseBody>() {
  @Override
  public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
    try {
      Log.i("onResponse", response.body().string());
    } catch (IOException e) {
      e.printStackTrace();
    }
  }

  @Override
  public void onFailure(Call<ResponseBody> call, Throwable t) {
    Log.e("onFailure", t.getMessage());
  }
});

Log.e("postjson", route);

结果:

具体代码已经传到github

PS:本文中服务器都是楼主在局域网搭建的,

需要添加的依赖:

compile 'com.squareup.retrofit2:retrofit:2.0.2'
compile 'com.squareup.retrofit2:converter-gson:2.0.0-beta3'

源代码下载

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持我们。

(0)

相关推荐

  • Android中Retrofit 2.0直接使用JSON进行数据交互

    之前使用Retrofit都是将JSON串转化为POJO对象,针对不同的业务协议,定义相应的接口和参数列表.但是此种方式一般用在自己内部协议基础上,具体大的项目中,有些第三方的集成功能,一般都采用统一的方式即请求JSON和回应JSON进行数据交互,不可能每个第三方协议都会去定义与协议相应的POJO对象. HTTP肯定有GET和POST方法,先定义Retrofit Api的interface: package com.hdnetworklib.network.http; import java.ut

  • Android如何通过Retrofit提交Json格式数据

    本文将介绍如何通过retrofit库post一串json格式的数据.首先post的json数据格式如下: { "Id": "string", "DeviceId": "string", "Name": "string", "SumDistance": 0, "RouteNo": "string", "SumPoints

  • 解析PHP 使用curl提交json格式数据

    复制代码 代码如下: $data = array("name" => "Hagrid", "age" => "36");$data_string = json_encode($data); $ch = curl_init('http://api.local/rest/users');curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");curl_seto

  • Android编程解析Json格式数据的方法

    本文实例讲述了Android编程解析Json格式数据的方法.分享给大家供大家参考,具体如下: package com.practice.json; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import android.app.Activity; import android.os.Bundle; import android.util.Log; public cla

  • Android编程简单解析JSON格式数据的方法示例

    本文实例讲述了Android编程简单解析JSON格式数据的方法.分享给大家供大家参考,具体如下: 比起XML,JSON主要优势在于它的体积更小,在网络上传输的时候可以更省流量.但缺点在于,它的语义性较差,显示不如XML直观. JSON格式 : { "name_A" : "value_A","name_B" : "value_B" } 表示: name_A = value_A; name_B = value_B; 我将对下面的J

  • Android解析JSON格式数据的两种方式(JSONObject和Gson)

    目录 Json数据 JSONObject GSON 添加依赖 实际操作 实体类 总结 Json数据 接下来主要学习在Android中使用两种解析方式:JSONObject和Gson. JSONObject 比如我们有如下格式的Json数据: [{"id":"1","verison":"1.0","name":"shufu"}, {"id":"2",

  • JS对象与JSON格式数据相互转换

    目前的项目数据交互几乎都用JQuery,所以处理流程是:前端页面数据->JS对象->jQuery提交->python处理,另外一种就是倒过来.python肯定不能直接处理JS对象数据,所以要把JS对象转换成为python能处理的一种数据格式(通常是字典dict),同样,python取数据反馈到前端也要把字典数据转换成JS能处理的对象,这个中间转换数据格式通常就是JSON. 一.JS对象转换成为JSON 流程:读取前端页面数据,组装成为JS对象,并通过jQuery的$.post()方法传递

  • SpringMVC环境下实现的Ajax异步请求JSON格式数据

    一 环境搭建 首先是常规的spring mvc环境搭建,不用多说,需要注意的是,这里需要引入jackson相关jar包,然后在spring配置文件"springmvc-servlet.xml"中添加json解析相关配置,我这里的完整代码如下: <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schem

  • django通过ajax发起请求返回JSON格式数据的方法

    本文实例讲述了django通过ajax发起请求返回JSON格式数据的方法.分享给大家供大家参考.具体实现方法如下: 这是后台处理的: def checkemail(request): user = None if request.POST.has_key('email'): useremail = request.POST['email'] result = {} user = User.objects.filter(useremail__iexact = useremail) if user:

  • jquery解析json格式数据的方法(对象、字符串)

    本文实例讲述了jquery解析json格式数据的方法.分享给大家供大家参考,具体如下: json数据是我们常用的一种小型的数据实时交换的一个东西,他可以利用jquery或js进行解析,下面我来介绍jquery解析json字符串方法. 一.jQuery解析Json数据格式: 使用这种方法,你必须在Ajax请求中设置参数: dataType: "json" 获取通过回调函数返回的数据并解析得到我们想要的值,看源码: jQuery.ajax({ url: full_url, dataType

  • 如何将ajax请求返回的Json格式数据循环输出成table形式

    首先,Ajax请求数据,(用的是Jquery的Ajax) 复制代码 代码如下: <script> $(function(){ $('#test').click(function(){ $.ajax({ url:'__APP__/Article/jsonTest', type:'post', success:function(data){ var item; $.each(data,function(i,result){ item = "<tr><td>&quo

随机推荐