I have always used a fromJson method to convert my json object to my model object. So let's say that my JSON has a car field which has my car models data, so I always parse the Json. Now I found out that it's also a common practice to use the json objects directly in the application. That has gotten me thinking
should I parse the json back to my models, if yes then why and if no then why not?
It depends but in general - yes, you should have transformation logic to convert your jsons (essentially, DTOs) into your entities (models as you call them). Here is my reasoning:
Your entities will likely be different from corresponding DTOs. As an example, your json model can have date/time information as long UTC msecs, but your entity model will likely be more usable if it has localized Date's
If you're exposing your entities (for example, as part of a library), you'll have much more flexibility in making changes to your remote apis (if such exist of course) without breaking your library's consumers codes
It completely depends on your project structure, if you have POJO classes defined in the models then converting them is the way to go. It makes your code more readable and fulfils your model which makes fetching the data easier. If you use a JSONObject directly then pulling data from it requires a bit more code. In terms of performance they both should have equal impacts since both are 'Objects' and will consume resources equally.
I vote for parsing them back to Models because of the simplicity it
enables for using those values further in your coding.
Related
I'm looking a way to improve the mapping mechanisms between the model classes from the different layers in my App.
I've model classes, the ones that I use in my App, in the business logic layer such as a Presenter. For example a User class.
I've server-side entities, these are the ones that I use to deserialize the responses from the server-side endpoints, through Retrofit or any other technology. These ones usually contain the Gson annotations for the fields. For example a ApiUserResponse class.
And I've DTO entities, these are the ones that represent a DB table in my App. I'm using Realm right now, but I've worked with ORMlite and Room. These types of classes also contain DB related annotations. For example a UserDTO class.
My cache repositories (the ones that fetch data from the DB) and my network repositories (the ones that fetch data from the server-side) both expose RxJava methods, returning the responses wrapped in Observable classes.
What I'm doing right now to parse the DTO entities and the server-side entities is add an extended function to the Observable class which receives a functions as argument. And that's the mechanism that I'm using to parse the DTOs and server-side entities into model classes. For example:
myLoginRepository.getUser("someId")
.mapTo(::myMappingFunction)
...
fun myMappingFunction(userResponse: ApiUserResponse): User {
return User(userResponse.id, userResponse.name, userResponse.lastname)
}
Internally the only thing that the mapTo extended function does is using a flatMap to flat the Observable stream and using a map to parse the collection.
I think that this is a pretty good way to implement the mapping between model-related classes, but I'm looking a way to improve it or do something completely different but that require less coding. Obviously this example is pretty straight forward, but currently I'm having a Mappings.kt file which is growing like crazy with each new mapping function.
Any suggestion?
Maybe http://modelmapper.org/ is something for you. This way you can spare your own mapping functions and you can even specify some sophisticated mapping functions. However it may cost you something in regards to performance (looks like reflection access all the way?).
Note: I didn't use the library myself yet, but it looks promising enough to recommend it. In the last project I helped out, they built their own modelmapper which probably wasn't such a good idea (lots of corner cases forgotten, which then led to strange behaviour later on or manually mapped the wrong fields; however your variant can suffer from that too).
Just found another article regarding mapping frameworks and their performance:
http://www.baeldung.com/java-performance-mapping-frameworks doesn't look that good for ModelMapper
You may also just want to generate your mapping functions. Similar to what you have now. Or just use a live template for it?
Manually writing your mappings may sooner or later introduce mistakes you are not identifying that easily anymore, except you test them all accordingly. Which you do, right? ;-)
You can convert your DTO object to entity or vice versa with converter.
Converter
ConversionService
You can implement Converter interface,It is a functional interface and you must implement convert method, then convert your DTO to entity, Where you want to convert them, just you should inject ConversionService and use convert method.
You should only have one class that representes both the entities and the model class from the network
If you want to use Room database and Retrofit for Api calls you should use like this
#Entity("tableName = something")
data class Something{
#SerializedName("name")
val name : String,
#SerializedName("number")
val number : Int}
I need to know the purpose of using JSON in android ?
Please anyone tell me in a simple way...
Thanks
The same reason you'd use it on any platform. JSON is a way of storing and expressing information. It uses attribute-value pairs in a hierarchical structure. In Android specifically, you may need to download some information from a database, which could be stored in JSON and then read by your app. Alternatively, you could store data locally in JSON but there are probably better and more efficient ways to do that if you're not sending data across a network.
https://en.wikipedia.org/wiki/JSON
JSON is very light weight, structured, easy to parse and much human readable. JSON is best alternative to XML when your android app needs to interchange data with your server
For example, you can get data Json if you work with database. Or if you work with some API's then you can get data in format Json.
For example an app could fetch data from a server. When using JSON to get the data, the traffic is quite small and the app can easily work with it.
For example you have a server with a database with recipes, and your app displays recipes, the app could ask the server for recipes, and it gets a JSON in return. for example:
{
name: 'Cookies'
ingredients: { 'Butter', 'Eggs', ... /* I don't know, I'm not a chef :D */
...
}
The app can then just read the properties and display them in a neat list ;)
JSON (JavaScript Object Notation) is a lightweight format that is used for data interchanging. It is also a subset of JavaScript's Object Notation (the way objects are built in JavaScript
Pls go through this link: http://www.copterlabs.com/blog/json-what-it-is-how-it-works-how-to-use-it/
JSON stands for JavaScript Object Notation
JSON is lightweight text-data interchange format
JSON is language independent *
JSON is "self-describing" and easy to understand
* JSON uses JavaScript syntax for describing data objects, but JSON is still language and platform independent. JSON parsers and JSON libraries exists for many different programming languages.
Using JSON in Android is not different than using it on any other platform. The main advantage of the format (in comparison to XML for example) is the small size of the data. This is very important for mobile devices due to the scarce resource those application use - i.e. your mobile app should be able to run with little memory usage, slow internet connection and so on.
Besides Android's framework has built-in tools for parsing / creating JSON objects. Thus it is both easy and efficient to use JSON rather than XML. If you have any project specific reason to prefer another data presentation format - don't worry. It is perfectly fine NOT to use JSON as long as some other format is more suitable for your project.
In short JSON is usually the right choice due to its small footprint and easy of use.
I have an application where I use Jsoup to get HTML file from the internet and parse it into POJOs. I use a custom Content Provider then to persist my POJOs into an SQLite database. It's a lot of code, and certain things are tricky to implement, caching especially (i.e. how to determine that my object is already in database, how to manage expiration, etc.). From looking over the internet I understood that RoboSpice might come to the rescue, since in handles caching transparently. However, I haven't found any example on how to plug in custom parser (my results are neither JSON nor XML, just pure HTML which I'm parsing with Jsoup currently). I'd therefore appreciate if you could point me to some related example.
Here's a more detailed description of what I'm doing. My app reads certain website to get the lists of certain entries. Those entries are calendar-based, and I'm requesting them month by month. Every month's request returns me a list of entries from that month. I want to make those requests cacheable and queryable, therefore I need a database backend, so that I can run custom SQL queries against it. Which RoboSpice configuration should I use, which extensions, and which code samples could I refer to?
Thanks in advance.
It looks like a good idea to use RoboSpice here, but the way you want to use is a bit out of its natural scope.
Usually people annotation a Pojo, let's say for Jackson, and they request a webservice, then the result is parsed via jackson and you get your Pojo. RoboSpice will simply reformat your pojo into json using jackson as parsing / formatting is a considered a bijection.
In your case, you will have to call your own ObjectPersister for your Pojo class and take care of its persistence format yourself. As you store your pojos into a database, the RoboSpice ormlite module may help but it is still experimental.
Have a look at the sample of the ormlite module of RoboSpice.
I'm working with an app that connects to a PHP/MySQL server from which everything is returned in JSON format. For example, a list of users is returned as a JSONArray of JSONObject. Each object contains the individual user's information (name, location, phone number, etc).
In working with information in this format is is more efficient to leave everything in JSON format and only extract items from the array/objects as needed? Or is it better to extract everything from the JSONArrayand included objects to build a regular Array or ArrayList first?
JSONArray internally uses ArrayList. It's just wrapper over ArrayList. So I'd say there is no difference. JSONObject uses HashMap so again no real drawbacks.
In summary, JSON (which can be thought of a subset of JavaScript) is a lot leaner than XML. This has several positive side-effects
JSON is smaller than corresponding XML
JSON is faster, i.e. simpler syntax -> easier parsing (faster parsing)
JSON was that of JavaScript, I considered it to be a close relative. But JSON is something independent and JSON.org does a great job of describing JSON. It's also provides a compatibility library for JavaScript that adds support for JSON.parse and JSON.stringify when not supported by browsers.
While eval at the time (mid 2009) was used to evaluate JavaScript, it could also evaluate JSON, i.e. parse JSON, but it was considered unsafe, as it did allow arbitrary JavaScript to execute in its stead.
JSON just happens to be a very good fit for browsers and a natural way to evolve the platform due to its close relationship with JavaScript.
While XML might be considered to have better rigor due to the fact that you can type it, it is also those things that make it a lot slower (it is also a bit verbose in my opinion). But if this is something you really want, you should use it, XML is equally ubiquitous.
I will not go into a debate over dynamic or statically typed, but I will say this. It's really easy to add stuff on top of schema-free data and there are plenty of ways to do validation, regardless of schema or no schema.
I'm writing an application that communicates with a web API, which responds with JSON. Currently, I'm translating the JSON objects to Java objects using gson (which is awesome, by the way).
Now, I want to store some of these objects in an SQLite database. However, they have lots of properties that would never be used in queries (i.e. I won't be ORDERing, WHEREing, or anything like that with those properties), so I feel it's unnecessary to create columns for all of them. What I'm thinking of doing is:
Only have columns for the essential data that will be used when querying the database
Have one TEXT or BLOB column (which one do you recommend?) that stores the actual JSON, so I can recreate my Java object from it and access all the data.
This would both make my life easier and streamline my code (I would not have to write very different code when dealing with data from the API vs. data from the database).
However, although I see no downsides, it feels a bit fishy.
What kind of trouble do you think I would run into if I use this technique?
The main thing I wouldn't like about it is relying on the structure of the stored/retrieved JSON to be valid, since it's completely out of the hands of the database. Not that you can't take precautions against possible issues, but if the JSON is somehow truncated or otherwise compromised in a way that trips up the parser, you're then missing the entire object instead of just one invalid or truncated property. If that's an acceptable risk, then it's probably a reasonable technique.