How do I convert a JSONObject to class object? - android

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)

Related

json data fetching android

How do I fetch this data using json. I have tried this but not working. Im very much confused about how to fetch the below data. Any help appreciated
{
"sftid": [
"sfta"
],
"todate": 205618.268,
"today": 5307.174,
"sfta": 5093.717,
"sftb": 213.457,
"sftc": 0,
"cropday": 21,
"crushingday": 21,
"vtractor": 4535.075,
"vtruck": 532.687,
"vbcart": 239.412,
"yestitons": 6374,
"ytractor": 248,
"ytruck": 90,
"ybcart": 40,
"ycart": 48,
"hr1": 515.043,
"hr2": 625.651,
"hr3": 706.789,
"hr4": 626.796,
"hr5": 630.639,
"hr6": 608.053,
"hr7": 604.559,
"hr8": 776.187
}
JSONObject jobject = new JSONObject(response);
JSONObject jsonObj = jobject.getJSONObject("todate");
You can do something like this
JSONObject jobject = new JSONObject(response);
then
double todate = jobject.getDouble("todate");
and so on as per the data type
or simply you can use http://www.jsonschema2pojo.org/ which will help you to convert your json data to a model class which you can use to fetch the data easily.
For this you need to use Gson library.
So suppose you created class with above link as "Myresponse" the you can use it as
Gson gson = new Gson();
Myresponse data = gson.fromJson("<your json resopnse>",Myresponse.class);
I have added screenshot for the settings you need to do on jsonschema2pojo website
As you see your response contains one JSONObject which contains many elements, First element is an JSONArray rest can be taken as a double/String.
It goes as follows :
JSONObject json = new JSONObject(response);
JSONArray sftid_array = json.getJSONArray("sftid");
ArrayList<String> sftid = new ArrayList();
for(int i = 0; i < sftid_array; i++) {
sfid.put(sftid_array.getString(i));
}
double todate = json.getDouble("todate");
double today = json.getDouble("today");
double sfta = json.getDouble("sfta");
double sftb = json.getDouble("sftb");
.
.
.
and so on
You can also use Array to store data of JSONArray. Don't forget to put it in try catch as it may throw JSONException.
You could try:
JSONObject jobject = new JSONObject(response.toString());
JSONObject jsonObj = jobject.getJSONObject("todate");

How to parse a JSON string in android

My web service outputs a JSON string that I need to parse.
Could you please tell me how i can parse the given JSON string:
{
"access_token":"kfwsfdcscfnsdcfsdsdfsd6f7df9sd6f89sd6s",
"expires_in":3600,
"token_type":"bearer",
"scope":null,
"refresh_token":"5dfddf1d6dfd1fddgdgdg1dg56d1"
}
JSONObject mainObject = new JSONObject(Your_Sring_data);
JSONObject uniObject = mainObject.getJSONObject("university");
String uniName = uniObject.getJSONObject("name");
String uniURL = uniObject.getJSONObject("url");
JSONObject oneObject = mainObject.getJSONObject("1");
String id = oneObject.getJSONObject("id");
refer this link:
http://stackoverflow.com/questions/8091051/how-to-parse-json-string-in-android
String jsonString = ""; //This'll contain the jsonString you mentioned above.
JSONObject object = new JSONObject(jsonString);
String accessToken = object.getString("access_token");
Similarly fetch other values.
{ // represents json object node
"access_token":"kfwsfdcscfnsdcfsdsdfsd6f7df9sd6f89sd6s", // key value pair
To parse
JSONObject jb = new JSONObject("jsonstring");
String acess_token = jb.getString("acess_token"); // acess_token is the key
// similarly others
You can also use Gson to convert json string to java object.
http://code.google.com/p/google-gson/
Using Gson
Download the jar add to the projects libs folder
Then
public class Response {
String acess_token,expires_in,token_typerefresh_token;
}
Then
InputStreamReader isr = new InputStreamReader (is);
Gson gson = new Gson();
Response lis = new Gson().fromJson(isr, Response.class);
Log.i("Acess Toekn is ",""+lis.expires_in);
JSONObject jsonObject = new JSONObject(jsonString);

How add the elements of json to List in android?

I am new to Android application development.
In my application i have one Json file like ["India","USA"]
My requirement is add the elements of that Json file to ArrayList.
please help me to go forward.
thank you,
bye....
Reader reader = new StringReader(json);
JsonReader jsr = new JsonReader(reader);
JsonParser parser = new JsonParser();
JsonElement rawJson = parser.parse(jsr);
JsonArray asJsonArray = rawJson.getAsJsonArray();
for (JsonElement jsonElement : asJsonArray) {
jsonElement.getAsString();
}
or
Type collectionType = new TypeToken<Collection<Integer>>(){}.getType();
Collection<Integer> ints2 = gson.fromJson(json, collectionType);
Use GSON library in both the instances.

How to get location from Google Place API JSON (android)

I have type below to get Location array to get the latitude, but it can not work.
Is it any mistake in my code? And i can get the result, but i cannot get geometry.
JSONTokener jsonParser = new JSONTokener(strResult);
JSONObject jsonObject = new JSONObject(strResult);
JSONArray routeObject = jsonObject.getJSONArray("results");
routeObject.getJSONObject(0).getJSONArray("geometry").getJSONObject(0).getJSONArray("location").getJSONObject(0).getDouble("lat")
I do it in this way:
The google maps url:
http://maps.google.com/maps/geo?q="+fullAddress;
And I read it:
JSONObject response = new JSONObject(result);
JSONObject point = response.getJSONArray("Placemark").getJSONObject(0).getJSONObject("Point");
lat = point.getJSONArray("coordinates").getString(1);
lng = point.getJSONArray("coordinates").getString(0);
Hope it helps!
I never used google-places-api, but I just tried something. I just toke the example file from https://developers.google.com/maps/documentation/places/ place-search-response and copied it to a file as input. (edit: I am using http://code.google.com/p/google-gson/ to decode)
My code to decode the JsonFile looks like that and gives you the latitude you are looking for:
JsonParser parser = new JsonParser();
JsonObject obj = (JsonObject)parser.parse(new FileReader(path));
for(Entry<String, JsonElement> entry : obj.entrySet()) {
String key = entry.getKey();
System.out.println(key);
if(key.trim().equals("results".trim())) {
for(JsonElement ele2 : entry.getValue().getAsJsonArray()) {
System.out.println(ele2.getAsJsonObject().get("geometry").getAsJsonObject().get("location").getAsJsonObject().get("lat"));
}
}
}

Simplest Gson.fromJson example fails

Given the following code:
final class retVal { int photo_id; }
Gson gson = new Gson();
retVal ret = gson.fromJson("{\"photo_id\":\"383\"}", retVal.class);
I get ret set to null.
I'm sure I've missed something obvious out, as toJson with a class also fails, although hand-construction through JsonObject works.
Declare your class retVal outside the method.
Gson helps you to serialize objects. So, you need an object first. Based on your approach, you want to do something like
RetVal myRetVal = new RetVal();
Gson gson = new Gson();
String gsonString = gson.toJson(myRetVal);
To retrieve the object back from the string:
Gson gson = new Gson();
RetVal myNewRetValObj = gson.fromJson(gsonString, RetVal.class);

Categories

Resources