Android parse json list with unknown attribute names - android

I need to parse a json with the structure as follows:
{
"names": {
"nameOne": {
"item": "my item"
},
"nameOther": {
"item": "my item 2"
},
... more elements with no prevously known attribute name
}
}
How could i retrieve it if i do not know how many nameOne, nameOther...nameX exist? My problem is to model that json, so i can not use a SerializedName. I think maybe exists something like a hashmap to store that objects.

use like this
#Expose
#SerializedName("names")
private HashMap<String, String> map;
map key will contains 'nameOne,.......'
use Gson as json parsing

This is not valid JSON structure. Anyway you can check this
How to parse JSON Array (Not Json Object) in Android
for parsing a JSON list it is not important how many elements will be in list. Do the simple for loop through the list elements and voila. Or even better use create something like this to parse a response :
public class Foo {
private List<Names> objects;
}
and you can use serializable here

you can loop through jsonObject's keys and add them to a map
Object obj = new JSONParser().parse(new FileReader("JSONExample.json"));
JSONObject jo = (JSONObject) obj;
Iterator<String> keys = jo.keys();
while(keys.hasNext()) {
String key = keys.next();
if (jo.get(key) instanceof JSONObject) {
// do something with jsonObject here
}
}

Related

Parsing inner int json object in android

I have already checked other posts of Stack Overflow regarding Json data parsing but did not find the solution to parse inner Json int objects.
I am getting the following response from a web service.
{
"counter":[
{
"1":[
{
"message":"28",
"events":0,
"shared_files":"8"
}
],
"2":[
{
"message":"39",
"events":"4",
"shared_files":"7"
}
]
.....
"n":[
{
"message":"39",
"events":"4",
"shared_files":"7"
}
]
}
]
}
Where "1", "2" and "n" are ids and json object size changes according to the data. I am able to parse the above response till JsonObect using following code:
JsonArray jsonArray = GetJson_.getArray(response, "counter");
if (jsonArray != null) {
JsonObject object = jsonArray.get(0).getAsJsonObject();
}
and my jsonObject now looks like
{
"1":[
{
"message":"28",
"events":0,
"shared_files":"8"
}
],
"2":[
{
"message":"39",
"events":"4",
"shared_files":"7"
}
]
.....
"n":[
{
"message":"39",
"events":"4",
"shared_files":"7"
}
]
}
But I am stuck at how to parse the JsonObject which is dynamic.
Please help.Thanks in advance.
hey you may use HashMap<> for parse dynamic key response for this check this link, other way you may use Iterator which i done below :
JSONObject jsonObject= m_jArry.getJSONObject(0);
Log.e("ad","--------"+jsonObject.toString());
Iterator keys = jsonObject.keys();
while(keys.hasNext()) {
// loop to get the dynamic key
String currentDynamicKey = (String)keys.next();
// get the value of the dynamic key
JSONObject currentDynamicValue = jsonObject.getJSONObject(currentDynamicKey);
// do something here with the value...
}
Hope this will helpful to you.

Jackson - Store nested json object as JSONObject

I am deserializing a json object, which contains a nested json object.
{
"id:" 1,
"name:" "test",
"settings": {
"color": "#ff0000"
}
}
Here is my Car class:
public class Car {
private long id;
private String name;
private JSONObject settings;
// id getter/setter...
// name gett/setter...
public void setSettings(JSONObject settings) {
this.settings = settings;
}
public JSONObject getSettings() {
return settings;
}
}
I would like to keep settings as a JSONObject and parse it later as I need it. I am also wanting to avoid creating a Settings class (because of how I'm caching my models with Sugar ORM). When I try to deserialize this with Jackson, settings is always returning "{}". How can I do this with Jackson?
UPDATE:
Here is the code that parses Car:
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
Car car = objectMapper.readValue(jsonObject.toString(), Car.class);
Car may be a nested object inside of something else, so this won't always be called. If I could always call this, this I would already have access to the json object and could just set the Settings object to the Car manually here.
Changing JSONObject to JsonObject seemed to have fixed the problem.

How to parse JSON without title object in Android?

I've a json output which returns something like this :
[
{
"title":"facebook",
"description":"social networking website",
"url":"http://www.facebook.com"
},
{
"title":"WoW",
"description":"game",
"url":"http://us.battle.net/wow/"
},
{
"title":"google",
"description":"search engine",
"url":"http://www.google.com"
}
]
I am familiar with parsing json having the title object, but i've no clue about how to parse the above json as it is missing the title object. Can you please provide me with some hints/examples so i can check them and work on parsing the above code?
Note : I've checked a similar example here but it doesn't have a satisfactory solution.
Your JSON is an array of objects.
The whole idea around Gson (and other JSON serialization/deserialization) libraries is that you wind up with your own POJOs in the end.
Here's how to create a POJO that represents the object contained in the array and get a List of them from that JSON:
public class App
{
public static void main( String[] args )
{
String json = "[{\"title\":\"facebook\",\"description\":\"social networking website\"," +
"\"url\":\"http://www.facebook.com\"},{\"title\":\"WoW\",\"description\":\"game\"," +
"\"url\":\"http://us.battle.net/wow/\"},{\"title\":\"google\",\"description\":\"search engine\"," +
"\"url\":\"http://www.google.com\"}]";
// The next 3 lines are all that is required to parse your JSON
// into a List of your POJO
Gson gson = new Gson();
Type type = new TypeToken<List<WebsiteInfo>>(){}.getType();
List<WebsiteInfo> list = gson.fromJson(json, type);
// Show that you have the contents as expected.
for (WebsiteInfo i : list)
{
System.out.println(i.title + " : " + i.description);
}
}
}
// Simple POJO just for demonstration. Normally
// these would be private with getters/setters
class WebsiteInfo
{
String title;
String description;
String url;
}
Output:
facebook : social networking website
WoW : game
google : search engine
Edit to add: Because the JSON is an array of things, the use of the TypeToken is required to get to a List because generics are involved. You could actually do the following without it:
WebsiteInfo[] array = new Gson().fromJson(json, WebsiteInfo[].class);
You now have an array of your WebsiteInfo objects from one line of code. That being said, using a generic Collection or List as demonstrated is far more flexible and generally recommended.
You can read more about this in the Gson users guide
JSONArray jsonArr = new JSONArray(jsonResponse);
for(int i=0;i<jsonArr.length();i++){
JSONObject e = jsonArr.getJSONObject(i);
String title = e.getString("title");
}
use JSONObject.has(String name) to check an key name exist in current json or not for example
JSONArray jsonArray = new JSONArray("json String");
for(int i = 0 ; i < jsonArray.length() ; i++) {
JSONObject jsonobj = jsonArray.getJSONObject(i);
String title ="";
if(jsonobj.has("title")){ // check if title exist in JSONObject
String title = jsonobj.getString("title"); // get title
}
else{
title="default value here";
}
}
JSONArray array = new JSONArray(yourJson);
for(int i = 0 ; i < array.lengh(); i++) {
JSONObject product = (JSONObject) array.get(i);
.....
}

How to parse a JSON with dynamic “key” in android by using GSON

I have been using GSON library to parse all the json string and get a JSON object.
But now I need to parse is like this:
{
"status":1,
"info":[
{
"\u5a31\u4e50":"\u51b7\u76d8,\u9ad8\u811a\u676f,\u6211\u7684\u7cd6\u679c\u5c4b,\u670d\u52a1\u4e1a\u6d88\u8d39\u52b5"
},
{
"\u7f8e\u5986":"\u4e2a\u62a4|\u5316\u5986#\u9762\u90e8\u62a4\u7406,\u4e2a\u4eba\u536b\u751f,\u8eab\u4f53\u62a4\u7406,\u9999\u6c34\u9999\u6c1b,\u6c90\u6d74|\u7f8e\u53d1\u7528\u54c1,\u5f69\u5986,\u7cbe\u6cb9SPA,\u773c\u90e8\u62a4\u7406,\u78e8\u7802\u53bb"
},
{
"\u8863\u670d":"\u670d|\u9970|\u978b|\u5e3d#\u670d\u88c5,\u978b\u9774,\u5185\u8863,\u914d\u9970,\u536b\u8863,\u4f11\u95f2\u88e4,T\u6064,\u88d9\u5b50,\u886c\u886b,\u9488\u7ec7\u886b,\u5a74\u5e7c\u513f\u670d\u9970"
}
],
"total":3
}
The key fields are dynamic, so I don't know how to write a model class to read this.
How would you like your model class to look?
status and total would probably be int, so that only leaves info.
As an experiment, just add a field Object info and see how Gson would set it to an ArrayList<LinkedHashMap<String, String>> -- ugly and hard to access by key, but all the data is there. Given that information, the fastest way to model a class would be:
class Something {
int status;
List<Map<String, String> info;
int total;
}
If you have control over how that JSON is generated, I suggest changing the structure of info from an array of objects [{a:b},{c:d},{e:f}] to just an object {a:b,c:d,e:f}. With this, you could just map it to a Map<String, String> with all the benefits like access by key, keys() and values():
class Something {
int status;
Map<String, String> info;
int total;
}
If you want the latter model class without changing the JSON format, you'll have to write a TypeAdapter (or JsonDeserializer if you're only interested in parsing JSON, not generating it from your model class).
Here's a JsonDeserializer hat would map your original info JSON property to a plain Map<String, String>.
class ArrayOfObjectsToMapDeserializer
implements JsonDeserializer<Map<String, String>> {
public Map<String, String> deserialize(JsonElement json, Type typeOfT,
JsonDeserializationContext context) throws JsonParseException {
Map<String, String> result = new HashMap<String, String>();
JsonArray array = json.getAsJsonArray();
for (JsonElement element : array) {
JsonObject object = element.getAsJsonObject();
// This does not check if the objects only have one property, so JSON
// like [{a:b,c:d}{e:f}] will become a Map like {a:b,c:d,e:f} as well.
for (Entry<String, JsonElement> entry : object.entrySet()) {
String key = entry.getKey();
String value = entry.getValue().getAsString();
result.put(key, value);
}
}
return result;
}
}
You need to register this custom JsonDeserializer similar to this:
GsonBuilder builder = new GsonBuilder();
builder.registerTypeAdapter(
new TypeToken<Map<String, String>>() {}.getType(),
new ArrayOfObjectsToMapDeserializer());
Gson gson = builder.create();
Note that this registers the custom deserializer for any Map<String, String> regardless in what class it is encountered. If you don't want this, you'll need to create a custom TypeAdapterFactory as well and check the declaring class before returning and instance of the deserializer.
Here goes a solution, which does not requires to make a JsonDeserializer.
All you can create is a JsonElement in a map Map.Entry<String, JsonElement>and use a for loop to iterate over the entries
//parsing string response to json object
JsonObject jsonObject = (JsonObject) new JsonParser().parse(jsonString);
//getting root object
JsonObject dateWiseContent = jsonObject.get("rootObject").getAsJsonObject();
for (Map.Entry<String, JsonElement> entry : dateWiseContent.entrySet()) {
//this gets the dynamic keys
String dateKey = entry.getKey();
//you can get any thing now json element,array,object according to json.
JsonArray jsonArrayDates = entry.getValue().getAsJsonArray();
}
read more here

Could someone help me with parsing this JSON file?

I have this JSON file:
{
"ics_desire":{
"version":"Beta 0.1.1",
"description":"description here",
"build-fingerprint":"fingerprint"
}
Now I want to put the version part in a txtVersion textview and the description part in the txtDescription textview.
Would someone help me?
So first off to state what was said above you JSON code is incorrectly formatted. You can validate you have correctly formated JSON code by going to http://json.parser.online.fr/.
Your correct JSON would be as follows (you were missing a closing })
{
"ics_desire": {
"version": "Beta 0.1.1",
"description": "description here",
"build-fingerprint": "fingerprint"
}
}
Next, here is an example of a working JSON code that I have used to test with in the past.
{
"HealthySubstituteData": [
{
"Assoc_ID": "1",
"uFood": "White Flour",
"hFood": "Wheat Flour",
"Category": "Baking",
"Description": "You can substitute blah blah blah...",
"Count": "5",
"submittedBy": "Administrator"
}
]
}
And here is the code I use to get that data.
ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();
JSONObject json = JSONfunctions.getJSONfromURL("http://your.url.com/whaterver");
try
{
JSONArray healthySubstituteData = json.getJSONArray("HealthySubstituteData");
for(int i=0;i<healthySubstituteData.length();i++)
{
HashMap<String, String> map = new HashMap<String, String>();
JSONObject e = healthySubstituteData.getJSONObject(i);
map.put("Assoc_ID", (String) e.get("Assoc_ID"));
map.put("uFood", (String) e.get("uFood"));
map.put("hFood", (String) e.get("hFood"));
map.put("category", (String) e.get("Category"));
map.put("description", (String) e.get("Description"));
map.put("count", (String) e.get("Count"));
map.put("submittedBy", (String) e.get("submittedBy"));
mylist.add(map);
}
}
So now I end up with an array list of type HashMap and I can do whatever I want with it at that point.
You can create a simple class like
public class Myclass{
String version;
String description;
String build-fingerprint;
};
and then use Gson to convert json to your object and vice versa:
Gson gson = new Gson();
Myclass obj = gson.fromJson(json_string, Myclass.class);
json_string should contain your jason string.
Now you can get your class objects values using getters.
Note: Gson is an external library you need to import, download it from google.
Ignoring about the missing brackets in JSON, this code would help you through
JSONObject json = JSONfunctions.getJSONfromURL("http://your.url.com/whaterver"); //the site where you get your JSON
JSONObject daata = json.getJSONObject("ics_desire"); //grabbing the inner object
String version = daata.getString("version"); //grabbing values
String description = daata.getString("description");
txtVersion.setText(version); //Hope you have initialized the Views.
txtDescription.setText(description);

Categories

Resources