Fast-Android-Networking icon indicating copy to clipboard operation
Fast-Android-Networking copied to clipboard

addJSONObjectBody using Gson not Json

Open winnerawan opened this issue 6 years ago • 2 comments

JSONObject jsonObject = new JSONObject();
try {
    jsonObject.put("firstname", "Rohit");
    jsonObject.put("lastname", "Kumar");
} catch (JSONException e) {
  e.printStackTrace();
}
       
AndroidNetworking.post("https://fierce-cove-29863.herokuapp.com/createUser")
                 .addJSONObjectBody(jsonObject) // posting json
                 .setTag("test")
                 .setPriority(Priority.MEDIUM)
                 .build()
                 .getAsJSONArray(new JSONArrayRequestListener() {
                    @Override
                    public void onResponse(JSONArray response) {
                      // do anything with response
                    }
                    @Override
                    public void onError(ANError error) {
                      // handle error
                    }
                });

the problem is when i use json, to create json object i got key "namevaluepairs" , i dont need that key, so how can i post gson instead of json ?

winnerawan avatar Dec 27 '18 07:12 winnerawan

my dataClass / ApprovalRequest.kt

package id.xxta.network.response.xx

import android.os.Parcelable
import com.google.gson.annotations.SerializedName
import kotlinx.android.parcel.Parcelize

@Parcelize
data class ApprovalRequest(

	

	@field:SerializedName("nm_company")
	val nmCompany: String? = null,

	@field:SerializedName("ttds")
	val ttds: List<TtdsItem?>? = null,

	@field:SerializedName("id")
	val id: String? = null,
) : Parcelable

@Parcelize
data class TtdsItem(

	@field:SerializedName("isSignatured")
	val isSignatured: Int? = null,
) : Parcelable

val gsonToJson = gson.toJson(ApprovalRequest) // but the properties required JSONObject so i tried with val gsonToJson = gson.toJson(ApprovalRequest) as JSONObject // but cannot be cast yaps i looking these,,, did u find solution ?

 java.lang.ClassCastException: java.lang.String cannot be cast to org.json.JSONObject

yogithesymbian avatar Nov 23 '21 23:11 yogithesymbian

ah solved by these https://stackoverflow.com/a/44350484/8122500

val data: String = gson.toJson(approvalRequest)
JSONObject(data)

yogithesymbian avatar Nov 23 '21 23:11 yogithesymbian