GSON sends my object as a string not a object - android

I am using Volley with GSON and I need to send a object as a parameter to my call.
This is how I do the object:
JSONObject params = new JSONObject();
Gson gson = new Gson();
String json = gson.toJson(route);
params.put("route", json);
And then I call my Volley JsonObjectRequest function.
The problem is that the params look like this:
{"route":"{\"bounds\":{\"northeast\":{\"lat\":52.3777194,\"lng\":4.924666999999999},\"southwest\":{\"lat\":52.36881109999999,\"lng\":4.9011479}},\"copyrights\":\"Map data ©2014 Google\", etc...}"
As you can see, instead of sending it as a object, its sending it as a String , and that's why I get the " before the {} (before the object begins). The params should look like:
{"route":{\"bounds\":{\"northeast\":{\"lat\":52.3777194,\"lng\":4.924666999999999},\"southwest\":{\"lat\":52.36881109999999,\"lng\":4.9011479}},\"copyrights\":\"Map data ©2014 Google\", etc...}
So no " before { like this:
{"route":{myObject}
What an I doing wrong here?

You don't want to mix JSONObject and GSON.
That's 2 different libraries.
Use gson.toJsonTree to obtain an element, then use JsonObject instead of JSONObject:
JsonObject params = new JsonObject();
Gson gson = new Gson();
params.add("route", gson.toJsonTree(route));

Related

How to parse and display that code of response Okhttp?

json want to parse and display link
that Is a response.body of Okhttp and I want parse and display it
Create a Java class that has the same structure as that jsonBody then Using gson library (add this to gradle implementation 'com.google.code.gson:gson:2.8.2') you can simply do this
JSONObject jsonObject = new JSONObject(response.body().string());
Gson gson = new Gson();
YourCLass yourClass = gson.fromJson(jsonObject.toString(), YourCLass .class);

Directly POST JSONObject via retrofit

Can I send JSON directly via retrofit like this:
#POST("rest/workouts")
Call<CreateWorkoutSuccessAnswer> createWorkout(#NonNull #Body JSONObject jsonObject);
You can use TypedInput
#POST("rest/workouts")
Call<CreateWorkoutSuccessAnswer> createWorkout(#NonNull #Body TypedInput body);
And to form param:
TypedInput in = new TypedByteArray("application/json", jsonObject.toString().getBytes("UTF-8"));
And use in as a parameter for request.
You can directly post JSON objects using GSONs JsonObject class.
The reason Googles JSONObject does not work is that retrofit uses GSON by default and tries to serialize the JSONObject parameter as a POJO. So you get something like:
{
"JSONObject":
{
<your JSON object here>
}
}
If what you are doing requires you to use JSONObject then you can simply convert between the two using the String format of the object.

json String in android

I have a problem while creating jsonStringer in android. My problem is I have to post values to server using post method.So for that I have to send an array. { "name":"asdf","age":"42","HaveFiles":["abcfile","bedFile","cefFile"]} .
So how can I create a json array for haveFiles? And I don't know the no of files it may varies. So I am creating a string builder and appending the values to that.
when I print the jsonString the stringbuilder show that instead of " it shows \". But when I print the string builder it looks ["abcFile"] like this. but in jsonStringer it prints ["\""abcFile\""]. How I can resolve this issue?
Use this to create json object and pass the json object
try {
JSONObject jObj = new JSONObject(YourString);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
If you want jsonArray then
jobj.getJSONArray(TAG_NAME);
It is really simple, you can use GSON library to do it.
The usage is something like:
Gson gson = new Gson();
String jsonStr = gson.toJson(yourObj);
YourObjType yourObj2 = gson.fromJson(jsonStr, YourObjType.class);
Regarding to your situation, you can do:
Gson gson = new Gson();
String[] ss = new String[] {"abcFile", "defFile", "ghiFile"};
String jsonStr = gson.toJson(ss);
And the result of jsonStr is:
["abcFile, defFile, ghiFile"]

How do I convert a JSONObject to class object?

I need to convert a JSONObject to a Location object using gson libraries for an android project of mine. I'm not sure on how to do this. Can anyone help me with this. Thanks in advance.
I have a code something like
JSONArray input = new JSONArray(extras.getString("loc_json"));
I wanted to convert the JSONObject taken from the JSONArray to a Location class object. I just wanted to know whether there is a function that does it directly.
Pardon me if I framed the question in a wrong way. Since I haven't got the direct function, I did it in this way.
loc_temp = (Location) gson.fromJson(input.getJSONObject(i).toString(), Location.class);;
Sorry for the stupid question.
Here's a tutorial for GSON - I think it should help bolster your understanding. Essentially the parsing is done like this:
String mJsonString = "...";
JsonParser parser = new JsonParser();
JsonElement mJson = parser.parse(mJsonString);
Gson gson = new Gson();
MyDataObject object = gson.fromJson(mJson, MyDataObject.class);
if you still want to use org.json.JSONObject:
org.json.JSONObject o;
ObjectMapper m = new ObjectMapper();
MyClass myClass = m.readValue(o.toString(), MyClass.class);
use com.google.gson.JsonObject & JsonArray instead of org.json.*
like this :
Gson gson = new Gson();
Type typeOfT = new TypeToken<List<Location.class>>(){}.getType();
JsonParser parser = new JsonParser();
JsonObject jo = (JsonObject) parser.parse(jsonStr);
JsonArray ja = jo.getAsJsonArray("memberName");
list = gson.fromJson(ja, typeOfT);
Convert JSONObject to Model class::
val jsonObject = JSONObject(data[0].toString())
val jsonModel = jsonObject.getJSONObject(KEY.message).toString()
val chatModel = Gson().fromJson(model, ChatModel::class.java))
For kotlin
val objType = object : TypeToken<MyClass>() {
}.getType()
var myclassObj = gson.fromJson(value,objType)
or
val objectResponse = Gson().fromJson(Gson().toJson(resp), MyClass::class.java)

create json in android

I wish to create json looking like:
{"man":
{
"name":"emil",
"username":"emil111",
"age":"111"
}
}
within android. This is what I have so far:
JSONObject json = new JSONObject();
json.put("name", "emil");
json.put("username", "emil111");
json.put("age", "111");
Can anyone help me?
You can put another JSON object inside the main JSON object:
JSONObject json = new JSONObject();
JSONObject manJson = new JSONObject();
manJson.put("name", "emil");
manJson.put("username", "emil111");
manJson.put("age", "111");
json.put("man",manJson);

Categories

Resources