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.
Related
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");
I have some JSON with the following structure:
{
"items":[
{
"product":{
"product_id":"some",
"price_id":"some",
"price":"some",
"title_fa":"some",
"title_en":"Huawei Ascend Y300",
"img":"some",
"has_discount_from_price":"0",
"discount_from_price":null,
"type_discount_from_price":null,
"has_discount_from_product":"0",
"discount_from_product":null,
"type_discount_from_product":null,
"has_discount_from_category":"0",
"discount_from_category":null,
"type_discount_from_category":null,
"has_discount_from_brand":"0",
"discount_from_brand":null,
"type_discount_from_brand":null,
"weight":null,
"features":[
{
"feature_value":"#000000",
"feature_id":"some",
"feature_title":"some"
},
{
"feature_value":"some",
"feature_id":"1652",
"feature_title":"some"
}
]
},
"number":1,
"feature_id":"56491,56493",
"price_inf":{
"has_discount":0,
"discount_type":0,
"final_price":"400000",
"value_discount":0
},
"cart_id":13
}
]
}
I'm trying to access the elements "product_id" and "price_id" with the following Java code:
try{
JSONArray feedArray=response.getJSONArray("items");
for (int i=0;i<feedArray.length();i++){
JSONObject feedObj=feedArray.getJSONObject(i);
JSONObject pro=feedObj.getJSONObject("product");
Product product = new Product();
product.setPrice(pro.getDouble("price_id"));
product.setTitle_fa(pro.getString("price_id"));}}
but i see product not found error.what is wrong in my parser?
First of all your JSON is valid. So no worries there.
Now regarding your problem, because you haven't posted the logs so I can't tell what the exact problem is. But using this code snippet you can get the desired values.
try {
JSONArray itemsJsonArray = jsonObject.getJSONArray("items");
for (int i = 0; i < itemsJsonArray.length(); i++){
JSONObject itemJsonObject = itemsJsonArray.getJSONObject(i);
JSONObject productObject = itemJsonObject.getJSONObject("product");
String productId = productObject.getString("product_id");
String priceId = productObject.getString("price_id");
}
} catch (JSONException e) {
e.printStackTrace();
}
Validate and create Pojo for your json here
use
Data data = gson.fromJson(this.json, Data.class);
follow https://stackoverflow.com/a/5314988/5202007
By the way your JSON is invalid .
you are getting a json object from your response not json array you need to make following changes
JSONObject temp =new JSONObject(response);
JSONArray feedArray=temp.getJSONArray("items");
Try converting response string to JSONObject first
try{
JSONObject temp =new JSONObject(responseString); // response is a string
JSONArray feedArray=.getJSONArray("items");
....
}
You may try to use GSON library for parsing a JSON string. Here's an example how to use GSON,
Gson gson = new Gson(); // Or use new GsonBuilder().create();
MyType target = new MyType();
String json = gson.toJson(target); // serializes target to Json
MyType target2 = gson.fromJson(json, MyType.class); // deserializes json into target2
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);
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)
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);