How to write and read contents containing complex json data? - android

friends:
I get a response from remote server as follows on Android:
{
"items": {
"persons": [
{
"id": "200120",
"name": "Bill"
},
{
"id": "200121",
"name": "Jim"
}
],
"tasks": [
{
"id": "001",
"name": "Fetch ten books",
"deadline": "5:30 p.m.",
"scores": "10"
},
{
"id": "002",
"name": "Fetch thirty books",
"deadline": "5:30 p.m.",
"scores": "30"
}
],
"intro": "This is a funny game."
},
"otherObj": []
}
And I want to save it to phones. I do not think it a good choice to save it into databases. However it read not fast if put the response to SharedPreferences file. Is there any other way?

No need to save this data into database as these value are dynamic and will change time to time.
In your Activity, call the API and get JSON as response and then parse this JSON and show it on device.
To store it on device u can use Singleton class also.
For JSON parser refer to http://www.tutorialspoint.com/android/android_json_parser.htm

You can first save your data into objects and at last into Object Array and then Save to database.(If your data is dynamic it is better you only deal with Object not database)
For saving to database you can use
db.beginTransaction();
for(object : ObjectArray){
db.dboperation();
}
db.setTransactionSuccessful();
db.endTransaction();

Related

How to use json in Android with Retrofit

In my application I want get some data from server and show this into list (recyclerview)!
I receive data from server such as below :
"data": {
"id": 1812286134,
"Cr": "85",
"BUN": "87",
"ALP": "75",
"ALT": "6",
"AST": "6",
"Chol": "55",
"HDL": "545",
"LDL": "45",
"TG": "4",
"created_at": "2022-10-30 16:05:50",
"updated_at": "2022-10-30 16:05:50"
}
UPDATE :
This data may update in some time, added new items or remove items by admins
I should show all of this items into recyclerview.
I know in above json data should list but has object.
But backend developer tells me convert all of this data to list with key value!
My question is can I convert this data to list and use all of items into list ?
How can I it?
Try to use Map<String,String> in your Response or whatever you used.
It will be something like this.
#GET
fun getCurrency():Response<DataResponse>
data class DataResponse(
val currencies:Map<String,String>
)

How to insert nested json into SQLite Flutter

I want to make a categories screen, the backend returns a nested json with 4 trees in total if I'm not mistaken,
example:
when I press the most general tree of the categories, I would like it to be displayed as a dropdown and there, put the children of this category, the ones that come in the json clearly, hope to explain myself well.
I have to fill these widgets, their text or titles with the text that comes clearly in the json, but I'm not going to be calling the endpoint every time I want to paint the titles, i have to save what comes in the json in the sqlite, and then extract from there the texts to put on categories screen ... how can I do this? I'm new, never build a structure like that, I have to do it with sqlite, but I wouldn't know how to start or how to build the tables, if I make a table, only the first tree of the categories will go, and the rest? the children of the nested json? Could someone guide me?
I leave you a piece of the json (for other reasons I can not put it complete) to put them a little more in context
{
"res": 0,
"categorias": [
{
"id": 1,
"name": "Bolsas",
"img": "hogar.png",
"titulo": 0,
"children": [
{
"id": 11,
"name": "Para llevar",
"img": "llevar.png",
"titulo": 0
},
{
"id": 12,
"name": "Para Conservar",
"img": "consrvar.png",
"titulo": 0
},
{
"id": 13,
"name": "Para Organizar",
"img": "organizar.png",
"titulo": 0
},
{
"id": 14,
"name": "Multipack",
"img": "multipack.png",
"titulo": 0
}
]
},
{
"id": 2,
"name": "Cuidado del aire",
"img": "aire.png",
"titulo": 0,
"children": [
{
"id": 21,
"name": "Instantaneo",
"img": "instantaneo.png",
"titulo": 0,
"children": [
{
"id": 211,
"name": "Aerosol",
"img": "llevar.png",
"titulo": 0
},
{
"id": 212,
"name": "Toque",
"img": "consrvar.png",
"titulo": 0
}
]
},
You have several option to work with json and sqlite:
Just put your json as string in row on table and then select as string and convert to json.
You can use similar approach from paragraph 1 bud with using sqlite's json extension. It adds possibility to select of update parts of json by special query syntax. To use sqlite with this extension u will need custom build of sqlite like sqlite-android (with have many other benefits).
You can crate separate sqlite table from each level fo json nesting (depends on your need of granularity). For example you can create table categorias with columsn(categorias_id, categorias_name, categorias_img, categorias_titulo), table categorias_childrens with columns(categorias_id, id, name, img, titulo, categorias_childrens_id).
In this case all rows of categorias_childrens table related with categorias.categorias_id contains categorias.categorias_id in categorias_childrens.categorias_id column. And all rows related with some of categorias_childrens row contains categorias_childrens.categorias_id in categorias_childrens.categorias_childrens_id column (situation when children.id.21 has childrens ).
Or u can combine approaches fro example: create table categorias with columsn(categorias_id, categorias_name, categorias_img, categorias_titulo, children) where column children will be contains string json value.

Query problem using sembast (NoSql) with flutter

I'm very new to NoSql databases, and I just want to ask you an easy question about the use of sembast! I'm developing a very simple app with flutter, and I want to get the object inside the array "list" with the "name" equal to 1.
{
"id": 12345,
"list": [{
"name": 1,
"element": [{
"nameItem": "a"
}, {
"nameItem": "b"
}]
}, {
"name": 2,
"element": []
}, {
"name": 3,
"element": []
}]
}
So I want to make a query that retrieves me this information:
{
"name": 1,
"element": [{
"nameItem": "a"
}, {
"nameItem": "b"
}]
}
I've written this code, but it doesn't work: I don't understand how to make a query with a subtag as a key in the json tree.
Future<List<ElementList>> getElementFromList(int name) async{
final finder = Finder(filter: Filter.equals("name", name));
final recordSnapshot = await _elementList.find(await _db, finder: finder);
return recordSnapshot.map((snapshot){
final elementObj = ElementList.fromJson(snapshot.value);
return elementObj;
}).toList();
}
this returns me []. How can I solve the problem?
Thank you in advance!
Sembast queries allow to filter records, not part of a record. If the object you mention is a whole record, you can:
use custom filter to perform the lookup yourself for each record in the database (checking each item in the list field`)
when a record is retrieved, extract the item (doing a similar Map/List manipulation)
See an issue with a complex filtering

How to access String name and price from this JSON data?

I have established a connection but unable to access data.Help needed
JSON data
[
{
"name": "Margherita",
"price": 170
},
{
"name": "Corn MAnia",
"price": 170
},
{
"name": "Triple Tango",
"price": 210
}
]
In MarkLogic Server, you can use the XPath language to traverse JSON and retrieve data. Code can be written in the Xquery language or Server Side JavaScript:
xquery version "1.0-ml";
let $doc:= xdmp:unquote('{"root":[{"name": "Margherita","price": 170}, {"name": "Corn MAnia","price": 170}, {"name": "Triple Tango","price": 210}]}')
return xdmp:document-insert('/doc/names.json', $doc)
To get data, use:
doc('/doc/names.json')/root[1]/name
or
doc('/doc/names.json')/root[2]/price/data()

Jackson deserializing JSON into multiple POJOs

Hi I have following JSON
{
"code": 0,
"response": {
"userObject": {
"User": {
"id": "355660",
"first_name": "Dummy",
"last_name": "dummy",
"email": "dumb#email.com",
"birthday": "2012-05-07",
"created": "2012-08-21 06:41:05",
"modified": "2012-08-21 06:41:05",
"image_url": null,
},
"Location": {
"id": "273550",
"name": "New York City",
"asciiName": "New York City",
"lat": "40.714272",
"lon": "-74.005966",
"geoname_modified": "2011-11-08 00:00:00",
"timeZone": "America/New_York",
"countryName": "United States",
"state": "New York",
"created": "2012-07-12 12:11:01",
"modified": "2012-08-20 14:27:24"
}
}
}
}
I have two classes, one each for Location and User
I know that I can get the objects if I create nested class like
response
->UserObject
*User
*Location
But i don't want to create two extra classes for UserObject and response just for wrapping the two POJO's .
Is there any simpler way to do it??
I am using Jackson Parser with Spring for android
You can also do it in two steps, if you really want to avoid throw-away classes, like:
JsonNode tree = mapper.readTree(...);
User user = mapper.treeToValue(tree.path("response").path("userObject").get("User"), User.class);
Location loc = mapper.convertValue(tree.path("response").path("userObject").get("Location"), Location.class);
but yeah I might go with silly struct-classes instead:
static class Response {
public UserObject userObject;
}
static class UserObject {
public Location Location;
public User User;
}
since it really isn't much more code.
Rather than creating classes you could create arrays or use hashmap. Personally, I would just create the classes. I think that this give you more flexibility in your app, and will allow you to work with the objects with less hassle. I know it takes time to set them up, but once you do that, you can use ArrayList and you can parse the JSON quite a bit easier.

Categories

Resources