I have json response in this form:
String json = "{\"0\":{ \"title\" :\"title 1\" , \"time\" : \"15:00\" } ,\"1\":{ \"title\" : \"title 2\" , \"time\" :\"16:00\" }}";
And here is my class, I am trying to map it to:
public class News implements Seriaizable{
#SerializedName("title")
private String title;
#SerializedName("time")
private String time;
}
I am struggling because i have an array without a name which contains loads of other arrays.
Gson gson = new GsonBuilder().setPrettyPrinting().create();
News obj = gson.fromJson(reader, News.class);
Would anyone be able to guide me into right direction?
Your JSON is incorrect in format. I have added some commas to correct it.
You can solve this problem by using maps :
String json = "{\"0\":{ \"title\" :\"title 1\" , \"time\" : \"15:00\" } ,\"1\":{ \"title\" : \"title 2\" , \"time\" :\"16:00\" }}";
Gson gson = new Gson();
Type type = new TypeToken<Map<Integer, News>>() {}.getType();
Map<Integer, News> map = gson.fromJson(json, type);
Ref : https://sites.google.com/site/gson/gson-user-guide#TOC-Collections-Examples
Related
I am using the Retrofit Library in Android to read the JSON data.
I want to only read the country names from the below JSON i.e just the value. Is it possible to read such JSON data using Retrofit Library?
{
"China": ["Guangzhou", "Fuzhou", "Beijing"],
"Japan": ["Tokyo", "Hiroshima", "Saitama", "Nihon'odori"],
"Thailand": ["Bangkok", "Chumphon", "Kathu", "Phang Khon"],
"United States": ["Mukilteo", "Fairfield", "Chicago", "Hernando", "Irving", "Baltimore", "Kingston"],
"India": ["Bhandup", "Mumbai", "Visakhapatnam"],
"Malaysia": ["Pantai", "Kuala Lumpur", "Petaling Jaya", "Shah Alam"]
}
List<String> list = new ArrayList<>();
Iterator<String> iter = json.keys();
while (iter.hasNext()) {
String key = iter.next();
list.add(key);
try {
Object value = json.get(key);
} catch (JSONException e) {
// Something went wrong!
}
}
Log.d("TAG",list.toString());
You can use HashMap<String,ArrayList<String>> as retrofit result obj and get the keys.
or just get it with string then cast it to hasmap
val typeToken: Type = object : TypeToken<HashMap<String, ArrayList<String>>>()
{}.type
val result = Gson().fromJson<HashMap<String, ArrayList<String>>>(tmp, typeToken)
then you can iterate trough the keys.
for example :
public class Country{
private List<String> name;
}
An associative array translates to a Map in Java:
Map<String, Country > countries = new Gson().fromJson(json, new TypeToken<Map<String, Country >>(){}.getType());
in retrofit just add to model class:
#Expose
private Map<String, Country> result;
Giving
JSON
// imagine this is JSON of a city
{
"title" : "Troy"
"people" : [
{
{
"title" : "Hector",
"status" : "Dead"
},
{
"title" : "Paris",
"status" : "Run Away"
}
},
...
],
"location" : "Mediteranian",
"era" : "Ancient",
...
}
City
public class City {
#SerializeName("title")
String title;
#SerializeName("people")
List<Person> people;
#SerializeName("location")
String location;
#SerializeName("era")
String era;
...
}
Person
public class Person {
#SerializeName("title")
private String title;
#SerializeName("status")
private String status;
}
If having string of JSON above, it is possible to create list of person
A. without having to deserialize City first like following
City city = new Gson().fromJson(json, City.class)
ArrayList<Person> people = city.people;
And
B. without having to convert string to JSONObject, get JSONArray and then convert back to string like following
String peopleJsonString = json.optJSONArray("people").toString
ArrayList<Person> people = new Gson().fromJSON(peopleJsonString, Person.class);
You can use a custom JsonDeserializer, which is part of Gson (com.google.gson.JsonDeserializer).
Simple example:
public class WhateverDeserializer implements JsonDeserializer<Whatever> {
#Override
public Whatever deserialize(final JsonElement json, final Type typeOfT, final JsonDeserializationContext context) throws JsonParseException {
Whatever whatever = new Whatever();
// Fetch the needed object here
// whatever.setNeededObject(neededObject);
return whatever;
}
}
You can then apply this deserializer like this:
Gson gson = new GsonBuilder()
.registerTypeAdapter(Whatever.class, new WhateverDeserializer())
.create();
There is a full example of how to use a custom deserializer, including a super detailed explanation, on this page: http://www.javacreed.com/gson-deserialiser-example/
I don't think you can get the list directly without parsing the json array. You need to parse the array. And it would be faster via Gson;
If you strictly need (only array) and you won't be using any other json object . Simply delete them, so that gson won't parse them.
I have a trouble finding a way how to parse this JSON.
{
"token":"3c7dbdc69c02eb365b2900d3e5027a08c79fce43",
"profiles":["User","PartnerUser"],
"status":"OK"
}
Plz,i need your hepl. I find atrouble with this "profiles":["User","PartnerUser"]
create a class that represent that json file and then parse it via GSon library:
Possible scenario:
Result.class
public class Result{
String token;
List<String> profiles;
String status;
//getter and setter
}
to parse json:
Gson gson = new Gson();
Result result = gson.fromJson(json, Result.class);
ArrayList<String> profiles = new ArrayList();
profiles = result.getProfiles();
check this
Are you using some library to perform JSON parsing?
If not, you can use the getJSONArray(..) method passing "profiles" as name of the array
Hello friends i have following JSON foramt
{
"Communities": [],
"RateLog": { "83": 5,"84": 4, "85": 5,"92": 5,"93": 4,"94": 5,"95": 5,"97": 5,"99": 4,"100": 5,"102": 5,"103": 5,"104": 5,"105": 5,"106": 5,"108": 4,"109": 4,"110": 4,"111": 5,"112": 4,"113": 4,"114": 4,"115": 5,"116": 5,"117": 5,"118": 4,"119": 5, "120": 5,"121": 4,"122": 5,"123": 4,"124": 4,"125": 4,"126": 5, "142": 5,"1150": 4, "1151": 4,"1152": 4, "1153": 4,"1154": 4, "1155": 4,"1156": 4, "1158": 5}
}
so how can i parse it any idea?
You can turn it into legal JSON by enclosing it in braces. So if you have the string:
var badJSON = '"RateLog" : { "1156": 4, ... }';
You can do this:
var goodJSON = '{' + badJSON + '}';
var parsed = JSON.parse(goodJSON);
EDIT: The above answer was before your edit. With the new format, the string is valid JSON, so simply call JSON.parse() and pass the string to get the corresponding object structure.
You must improve your json format like this :
"RateLog":[
{
id1:1156
id2:4
{
id1:1155
id2:4
}
{
id1:1155
id2:4
}
..]
JSONObject json = new JSONObject(jsonString);
JSONArray array = json.getJSONArray("Communities");
for (int i = 0; i < array.length(); i++) {
// do stuff
}
JSONObject rateJson = json.getJSONObject("RateLog");
rateJson.getInt("83"); //Will return 5
.
.
.
for more got through this tutorial
http://www.mkyong.com/java/json-simple-example-read-and-write-json/
You can use Google's Gson library to parse your response.
Using POJO class
String jsonString = "Your JSON string";
Pojo pojo = new Gson().fromJson(jsonString, Pojo.class);
class Pojo {
ArrayList<String> Communities;
HashMap<String, Integer> RateLog;
//Setters and Getters
}
Without using POGO class
Gson gson = new Gson();
String jsonString = "Your JSON string";
JsonObject jsonObj = gson.fromJson(jsonString, JsonElement.class).getAsJsonObject();
HashMap<String, Integer> RateLog = gson.fromJson(jsonObj.get("RateLog").toString(), new TypeToken<HashMap<String, Integer>>(){}.getType());
You can iterate through RateLog HashMap to get key, value pairs.
How to parse below Json Response with google Gson.?
{
"rootobject":[
{
"id":"7",
"name":"PP-1",
"subtitle":"name-I",
"key1":"punjab",
"key12":"2013",
"location":"",
"key13":"0",
"key14":"0",
"key15":"0",
"result_status":null
},
{
"id":"7",
"name":"PP-1",
"subtitle":"name-I",
"key1":"punjab",
"key12":"2013",
"location":"",
"key13":"0",
"key14":"0",
"key15":"0",
"result_status":null
},
{
"id":"7",
"name":"PP-1",
"subtitle":"name-I",
"key1":"punjab",
"key12":"2013",
"location":"",
"key13":"0",
"key14":"0",
"key15":"0",
"result_status":null
},
{
"id":"7",
"name":"PP-1",
"subtitle":"name-I",
"key1":"punjab",
"key12":"2013",
"location":"",
"key13":"0",
"key14":"0",
"key15":"0",
"result_status":null
}
]
}
I'd create objects to "wrap" the response, such as:
public class Response {
#SerializedName("root_object")
private List<YourObject> rootObject;
//getter and setter
}
public class YourObject {
#SerializedName("id")
private String id;
#SerializedName("name")
private String name;
#SerializedName("subtitle")
private String subtitle;
//... other fields
//getters and setters
}
Note: use #SerializedName annotation to follow naming conventions in your Java attribute while matching the names in the JSON data.
Then you just parse the JSON with your Reponse object, like this:
String jsonString = "your json data...";
Gson gson = new Gson();
Response response = gson.fromJson(jsonString, Response.class);
Now you can access all the data in your Response object using getters and setters.
Note: your Response object may be used to parse different JSON responses. For example you could have JSON response that don't contain the id or the subtitle fields, but your Reponseobject will parse the response as well, and just put a null in this fields. This way you can use only one Responseclass to parse all the possible responses...
EDIT: I didn't realise the Android tag, I use this approach in a usual Java program, I'm not sure whether it's valid for Android...
You can try this hope this will work
// Getting Array
JSONArray contacts = json.getJSONArray("rootobject");
SampleClass[] sample=new SampleClass[contacts.length]();
// looping through All
for(int i = 0; i < contacts.length(); i++){
JSONObject c = contacts.getJSONObject(i);
// Storing each json item in variable
sample[i].id = c.getString("id");
sample[i].name = c.getString("name");
sample[i].email = c.getString("subtitle");
sample[i].address = c.getString("key1");
sample[i].gender = c.getString("key12");
sample[i].gender = c.getString("location");
sample[i].gender = c.getString("key13");
sample[i].gender = c.getString("key14");
sample[i].gender = c.getString("key15");
sample[i].gender = c.getString("result_status");
}