Generate unique json object name gson in Kotlin - android

How would I be able to generate a new object based on the object names below. What I am trying to do here is that when there is no Object1, gson will generate Object1 with the values below and when there is Object1, gson will generate Object2 and so on.
{
"Object1": {
"Name": "Object1",
"Color": "Orange",
"Food": "Pizza"
},
"Object2": {
"Name": "Object2",
"Color": "Blue",
"Food": "Pineapple"
}
}

Generating an unique property in your class object means you could dynamically have a class lets say Example.
FoodData {
var object1 : Food?
var object2 : Food?
// And so on...
}
For me this seems like a structural problem. Your response should be specific to the data structure you have and need. A more acceptable approach would be:
[
{
"Name": "Object1",
"Color": "Orange",
"Food": "Pizza",
"someAttr" : "Object1"
},
{
"Name": "Object2",
"Color": "Blue",
"Food": "Pineapple",
"someAttr" : "Object2"
}
]
And then it would make more sense to have a list of food like :
FoodData {
var listFood: List<Food>?
}

Related

How to remove extra json object in flutter

This is my cart list and I'm converting into JSON object to send at the server
Map<String,dynamic> str={'cart':cartList};
cartitem = jsonEncode(str);
doing something like this but it is adding extra JSON object and this is invalid JSON form. then how can I remove extra JSON object.
{
{"cart":[
{
"cartid":2,
"pid":"342702",
"merchantId":"MER-07156",
"hashkey":"7087fea71afc963d6dc3fa04944008ec",
"productname":"Scheduling Product - Edit Please",
"product_image":"Scheduling Product - Edit Please",
"shipping_price":"0.00",
"state_tax_rate":"0.0",
"taxamt":"0.00",
"discountamt":"0.0",
"price":"10.00",
"pricewithattr":"17.00",
"quantity":"18",
"totalamount":"306.00",
"taxvalue":"0.0",
"attribute_array":"[{\"attributeid\":\"20796\",\"attributename\":\"Black\",\"groupname\":\"Color\",\"groupid\":\"3012\"},{\"attributeid\":\"20798\",\"attributename\":\"Silk\",\"groupname\":\"Cloth\",\"groupid\":\"3013\"},{\"attributeid\":\"20800\",\"attributename\":\"small\",\"groupname\":\"Size\",\"groupid\":\"3014\"}]",
"is_free":"0",
"is_payable_later":"0",
"isattrpresent":"1"
}
]
}}
Strange, because this code:
Map<String, dynamic> str = {
'cart': [1, 2, 3]
};
String cartitem = jsonEncode(str);
print(cartitem);
which does basically the same thing, produces valid json:
{"cart":[1,2,3]}
Try debugging by just json encoding one of the cart members, replacing the cart members by something simple (like an integer, above) until you find the issue.
Your JSON is not right structure.
Did you try to parse it any online converter?
You should remove { character before "cart" and remove } character the end of json.
I tried to debug and found that jsonEncode was adding an extra object so I converted cartiem into jsonEncode prior to adding into the map.
var cartitems2=cartList;
Map<String,dynamic> str={'"cart"':json.encode(cartitems2)};
cartitem = str.toString();
debugPrint('CART :-----${cartitem}');
Expected Result
{
"cart": [
{
"cartid": 22,
"pid": "342702",
"merchantId": "MER-07156",
"hashkey": "7087fea71afc963d6dc3fa04944008ec",
"productname": "Scheduling Product - Edit Please",
"product_image": "Scheduling Product - Edit Please",
"shipping_price": "0.00",
"state_tax_rate": "0.0",
"taxamt": "0.00",
"discountamt": "0.0",
"price": "10.00",
"pricewithattr": "26.00",
"quantity": "10",
"totalamount": "260.00",
"taxvalue": "0.0",
"attribute_array": [
{
"attributeid": "20794",
"attributename": "Red",
"groupname": "Color",
"groupid": "3012"
},
{
"attributeid": "20799",
"attributename": "Cotton",
"groupname": "Cloth",
"groupid": "3013"
},
{
"attributeid": "20800",
"attributename": "small",
"groupname": "Size",
"groupid": "3014"
}
],
"is_free": "0",
"is_payable_later": "0",
"isattrpresent": "1"
}
]
}

Gson - Named Object to Array

In the response from the server, the data is structured as named objects. I'm trying to figure out how I would convert it to an array with the details in specific fields.
Example response from the server.
{
"Value_1": { "Foo": "True", "Bar": "False"},
"Value_2": { "Foo": "False", "Bar": "False"},
"Value_3": { "Foo": "False", "Bar": "True"}
}
Example of preferred converted result from the server.
{[
{"Name": "Value_1",
"Details": [{"Name": "Foo", "Value": "True"},
{"Name": "Bar", "Value": "False"}]},
{"Name": "Value_2",
"Details": [{"Name": "Foo", "Value": "False"},
{"Name": "Bar", "Value": "False"}]},
{"Name": "Value_3",
"Details": [{"Name": "Foo", "Value": "False"},
{"Name": "Bar", "Value": "True"}]}
]}
How do tell gson to convert from the response to the preferred structure?
I was able to accomplish this in a fairly clean method using a custom JsonDeserializer. The main thing is JsonObject.entrySet(), which gives you the key/value pairs of the JsonObject so you can iterate over them.
First, when building your Retrofit client, add your custom JsonDeserializer.
gsonBuilder.registerTypeAdapter(MyModel::class.java, MyModelDeserializer())
And then implement it like this.
class MyModelDeserializer : JsonDeserializer<MyModel> {
override fun deserialize(json : JsonElement, typeOfT : Type?, context : JsonDeserializationContext?) : MyModel {
val jsonObject = json.asJsonObject
// Create a new ArrayList to store the values.
val list = ArrayList<MyModel>()
// Using entrySet, get each key/value pair. "Value_1: {...}"
for (entry in jsonObject.entrySet()) {
val valueName = entry.key // The key, which would be the name "Value_1"
// Creating a new ArrayList to contain all the data.
val vals = ArrayList<Pair<String, Boolean>>()
val values = entry.value.asJsonObject
// Using entrySet again for each value of the Object.
for (entry in values.entrySet()) {
vals.add(entry.key to entry.value.asBoolean)
}
// Create a new MyModel, with the correct name and values.
list.add(MyModel(valueName, vals))
}
return MyModel(list)
}
}

How to parse json array having dynamic keys using Retrofit 2

I am trying to fetch json response using retrofit 2. My json response looks like this :
[
0 : {
type : "video",
format : "mp4",
size : "10mb"
},
1 : {
type : "audio",
format : "mp3",
size : "10mb"
},
2 : {
type : "text",
format : "pdf",
size : "10mb"
}
]
How should my model class look like? I can't understand as it has dynamic keys.
This is not a valid Json as you can try that on https://jsonlint.com/ , you can change your response to :
[
{
"type":"video",
"format":"mp4",
"size":"10mb"
},
{
"type":"audio",
"format":"mp3",
"size":"10mb"
},
{
"type":"text",
"format":"pdf",
"size":"10mb"
}
]
first of all this is invalid/incomplete JSON. The valid version would look something like this
{
"items": [
{
"0": {
"type": "video",
"format": "mp4",
"size": "10mb"
}
},
{
"1": {
"type": "audio",
"format": "mp3",
"size": "10mb"
}
},
{
"2": {
"type": "text",
"format": "pdf",
"size": "10mb"
}
}
]
}
and it would safely deserialize to this
class Item{
String type;
String format;
String size;
}
class Response{
List<Map<Integer,Item>> items;
}
//....
Response response = new Gson().fromJson(yourJson, Response.class);
As an alternative solution, as I am sure you can't change the JSON format, change the [] to {} in your JSON string and deserialize it like this
Map fieldMap = (Map)new Gson().fromJson(json, Map.class);
it should give you a LinkedTreeMap of all your data
So, as people already said, if you change your json to be valid:
[
{
"type":"video",
"format":"mp4",
"size":"10mb"
},
{
"type":"audio",
"format":"mp3",
"size":"10mb"
},
{
"type":"text",
"format":"pdf",
"size":"10mb"
}
]
Then you can create your class, for instance:
public class Test {
public String type;
public String format;
public String size;
}
And then, with Gson:
Type testType = new TypeToken<ArrayList<Test>>(){}.getType();
ArrayList<Test> list = new Gson().fromJson(json, testType);
On the other hand, with retrofit2 you can get the Gson converter to do the job for you.

How to parse this JSON file to some ArrayList<String>?

in the past i have already parsed a json file from url to local sqlite database and the json source was like the following one:
[
{
"origin": "accommodation",
"parent": "",
"en": "Accommodation"
},
{
"origine": "book",
"parent": "shopping",
"en": "Book"
},
{
"origin": "university",
"parent": "education",
"en": "University"
}
]
But now it seems to be different. I validate the following json file so i'm sure it is a valid json, but it is formatted in a different way, so i do not know how to parse it in the right way. In addition this time i would put the content in an ArrayList. Here is the json file:
{
"city1": {
"item1": {
"score": 6196.58,
"step": 0.00423,
"name": "User 1",
"form": "yellow"
},
"item2": {
"score": 106.86,
"step": 2.5822,
"name": "User 2",
"form": "yellow"
},
"item3": {
"score": 671.48,
"step": 0.387,
"name": "User 3",
"form": "yellow"
},
},
"misc": {
"online_users": {
"kind1": 18,
"kind2": 3
},
"ops": [
""
]
},
"city2": {
"item1": {
"score": 6196.58,
"step": 0.00405,
"name": "User 1",
"form": "yellow"
},
"item2": {
"score": 179563.93,
"step": 0.000138,
"name": "User 2",
"form": "yellow"
},
"min_size": {
"line": 10
},
"out_of_sync": [
"0e888069530497506433b5f0cacb",
"b428fa3a9b9e13cf8b26196bfcc7",
"f42442a2e46523f059809f83f1a9"
],
},
}
Can you tell me how to handle these values and how to put in some arraylist?
There are several ways to do this, but I'll post the way I feel like makes the most sense. If you don't mind putting this in separate arrays you can do this:
String stringOfJSONCode = <read in the JSON here>;
JSONObject json = new JSONObject(stringOfJSONCode);
Iterator<String> iter = json.keys();
while (iter.hasNext()) {
String key = iter.next();
try {
Object value = json.get(key);
} catch (Exception e) {
}
}
You need to use an iterator to loop through a JSONObject. You could use any other loop to loop through JSONArrays. This will iterate through the outer objects, like city1, misc, city2. The key will be either city1, misc, or city2.
If you want to get those, just add this within the 'try'
JSONObject object = json.getJSONObject(key);
or
JSONArray array = json.getJSONArray(key);
depending on what you're trying to get. Once you have these, you can do the following:
JSONObject city1 = object.getJSONObject("item1");
List<String> jsonList = new ArrayList<String>();
jsonList.add(object.getDouble("score"));
jsonList.add(object.getDouble("step"));
jsonList.add(object.getString("name"));
jsonList.add(object.getString("form"));
If you are not sure if it will be item1 or whatever, you can iterate through it again using the iterator and add each item in dynamically. Also you can make another try-catch, try to get a JSONArray, if it is not an array it will go in the catch, and then iterate through the object.
You could also make a hashmap or 2D array to add everything in the same array.
Hope this helps
Why don't you let jackson mapper do it's magic?
The only thing you'll need then would be appropriate DTO classes.

get coordinates from JSON from google maps

I'm getting my position from an address, I use this website:
I get JSON data, but I dont know how to read it in my Android app.
{
"name": "plaza mayor 1 madrid España",
"Status": {
"code": 200,
"request": "geocode"
},
"Placemark": [ {
"id": "p1",
"address": "Plaza Mayor, 1, 28012 Madrid, España",
"AddressDetails": {
"Accuracy" : 8,
"Country" : {
"AdministrativeArea" : {
"AdministrativeAreaName" : "Comunidad de Madrid",
"SubAdministrativeArea" : {
"Locality" : {
"LocalityName" : "Madrid",
"PostalCode" : {
"PostalCodeNumber" : "28012"
},
"Thoroughfare" : {
"ThoroughfareName" : "Plaza Mayor, 1"
}
},
"SubAdministrativeAreaName" : "Madrid"
}
},
"CountryName" : "España",
"CountryNameCode" : "ES"
}
},
"ExtendedData": {
"LatLonBox": {
"north": 40.4164186,
"south": 40.4137207,
"east": -3.7053139,
"west": -3.7080118
}
},
"Point": {
"coordinates": [ -3.7066379, 40.4150359, 0 ]
}
} ]
}
How can I read the "coordinates" tag?
Thank you in advance!
parse it, to begin with, then access the various elements :
JSONObject response = new JSONObject(responseAsString);
JSONObject point = response.getJSONArray("Placemark").getJSONObject(0).getJSONObject("Point");
double lat = point.getJSONArray("coordinates").getDouble(0);
and so on
I would suggest using some sort of framwork to handle your Json data, here's a good aexample. Then you can handle your data as a regular object.
Sending and Parsing JSON Objects
Good luck!

Categories

Resources