Checkboxes checked into JSON Format in SpringMVC - java

I am working on a spring MVC application. I have a sitaution where i need to check some checkboxes from UI and save the checked values in the form of JSON in the backend and i need to convert that into a string.
The picture shows more.
So i want to save like:
[{
Coast : 'East',
States : [ 'NY', 'MI' ]
},{
Coast : 'Central',
States : [ 'TX', 'OK' ]
}].
Please suggest me how can i implement this.

Your question is quite vague so I'm going to assume because you've used the json tag that you're asking for help on how to model this information in JSON and handle it within your Spring app.
You probably want to restructure your JSON schema to support extra fields being set per state. Instead of States being a list of strings, you could change it to a list of objects which has a name and selected field.
I'd also recommend you change the keys in your JSON to be lower case, this enables more fluent mapping between your JSON and model classes.
For example, MI is selected in the below JSON, whereas NY isn't:
[{
"coast": "East",
"states": [{
"name": "NY",
"selected": true
}, {
"name": "MI",
"selected": false
}]
}, {
...same again for West and Central
}]
You could then have some classes along the lines of and use Jackson to map between them:
public class Region {
String coast;
List<State> states;
}
public class State {
String name;
boolean selected;
}

Related

ElasticSearch / Java - Dynamic Templates aggregation with null values included

I'm having a diffuculties with aggregations over dynamic templates. I have values stored like this.
[
{
"country": "CZ",
"countryName": {
"en": "Czech Republic",
"es": "Republica checa",
"de": "Tschechische Republik"
},
"ownerName": "..."
},
{
"ownerName": "..."
}
]
Country field is classic keyword, mapping for country name is indexed as dynamic template according to the fact that I want to extend with with another languages when I need to.
{
"dynamic_templates": [
{
"countryName_lsi_object_template": {
"path_match": "countryName.*",
"mapping": {
"type": "keyword"
}
}
}
]
}
countryName and country are not mandatory parameters - when the document is not assigned to any country, I can't have countryName filled either. However I need to do a sorted aggregation over the country names with according to chosen key and also need to include buckets with null countries. Is there any way to do that?
Previously, I used TermsValuesSourceBuilder with order on "country" field, but I need data sorted according to specifix language and name and that can't be done over country codes.
(I'm using elasticsearch 7.7.1 and java 8 and recreation of index / changing data structure is not my option.)
I tried to use missing bucket option, but the response does not include buckets with "countryName" missing at all.
TermsValuesSourceBuilder("countryName").field("countryName.en").missingBucket(true);

Extracting specific section of JSON from URL in Android?

I am bulding a small app to track Bike Stations around the city, and I have an API that gives me the current status of the availability of bikes in bike stations from the company that provides the service.
My plan is to have a sort of interactive map, with all the markers for each of the bike stations, and when the user taps one of these, they get the information on that specific bike station. I have already all the locations coded in as markers on the map. What I need now is to be able to get the data for the specific bike station the user clicks.
An example of a part of the JSON I get from the API is below:
"number": INT,
"contract_name": "STRING",
"name": "STRING",
"address": "STRING",
"position": {
"lat": DOUBLE,
"lng": DOUBLE
},
"banking": BOOLEAN,
"bonus": BOOLEAN,
"bike_stands": INT,
"available_bike_stands": INT,
"available_bikes": INT,
"status": "STRING",
"last_update": 1588583133000
},
....
This structure is the same for all 100+ nodes of the JSON which I get from the API.
My question is, how would I go about filtering out one individual entry like such from the rest of the JSON. The parameter number is an ID unique to each bike station.
Is there a library that can do this for me? My idea (Very naive) was to save the whole JSON locally each time, and then go through it looking for "number":X and then parse out the data I needed, although this is obviously highly inefficient, I recognize that.
I am only interested in a part of each JSON, to be show to the user: the node's banking, bonus, available_bike_stands, available_bikes and status tags. The status tag is optional, it should simply tell me if the bike station is open (available) or closed.
Thank you very much,
Regards.
Get data from API --> Retrofit
Save local data--> SharePreference, Room
get a part of each JSON --> you create an object that contains some fields you need. when you use retrofit get data from API then it will return the result you desire
class YourClass {
#SerializedName("number")
var number: Int? = null
#SerializedName("banking")
var banking: Boolean? = null
#SerializedName("bonus")
var bonus: Boolean? = null
#SerializedName("available_bike_stands")
var availableBikeStands: Int? = null
//... fields you need
}

Using two different structures in one Firebase database

I'm currently working on a project where I need two different types of non-related datastructures in my Java Android app. One being users, the other being types of food.
Users are set up like this:
users
userid
name
age
gender
weight
height
But, I also need one that looks like this, which must be searchable:
foods
name
carbohydrate
fat
protein
Is it possible to user the same database (preferrable Firebase, as I'm already using that), or do I need to add another database to the app I'm making?
Edit: I ended up exporting the JSON, rewriting it according to the good answers given here, and then importing it again. It works flawlessly. Thanks for your answers!
{
"foods" : {
"name" : {
"carbohydrates" : "5",
"fats" : "5",
"proteins" : "5"
}
},
"users" : {
"FjtMNTcDrOP2wcaPAa0E0Cc1jRz2" : {
"activity" : "Moderate Exercise (3–5 days/week)",
"age" : "40",
"gender" : "Male",
"height" : "180",
"name" : "Flex",
"weight" : "86"
}
}
}
Yes, it is possible to model multiple entity types (such as your users and foods) in the Firebase Realtime Database. While it doesn't have the concept of a table, it's a hierarchy of JSON values and you can model any structure you want in that.
For example, you could express you data model with this JSON:
{
"users": {
"userid": {
"name": "value",
"age": 42,
"gender: "value",
"weight": 190,
"height": 172
}
},
"foods": {
"name": {
"carbohydrate": 42
"fat": 11,
"protein": 8
}
}
}
In relational terms, the above model defines two "tables": users and foods. In Android code you can define separate references to each of these with:
DatabaseReference rootReference = FirebaseDatabase.getInstance().getReference();
DatabaseReference usersReference = rootReference.getChild("users");
DatabaseReference foodsReference = rootReference.getChild("foods");
Yes, you can use the same Firebase Realtime Database to store that data.
The RTDB can be simplified down to being just a JSON tree. So for your desired implementation, you would have two keys at the root of your database (such as "users" and "foods").
{
"users": {
"userid1": {
"name": "somestring",
"age": "somenum",
"gender": "somestring",
"height": "somenum",
"weight": "somenum",
...
},
...
},
"foods": {
"food1": {
"name": "somename",
"carbs": "somenum",
"fat": "somepercent",
"protein": "somepercent",
...
},
...
}
}
You can also add or remove more root keys as you wish and your project takes shape.
However,
As #Tamir Abutbul suggests in their answer, I would use Cloud Firestore for this project over the RTDB.
The reason for this is that based on your data, you are likely going to need to filter results by a number of different values at a time in the future. Cloud Firestore supports these types of queries natively (docs) whereas you'd need to write a custom solution for the RTDB.
Getting Started with Cloud Firestore
You can use Firebase with Cloud Firestore.
Create "users" collections with your wanted data structure and another collection called "foods" with its own data structure.
The next step is just to decide when to use any one of those collections(according to your app logic).

Best practice for "connecting" json objects

My json:
{
"activities": [
{
"type": "post",
"id": "160",
"name": "John Wayne",
"content": "this is the actual post",
"timestamp" : "date + time",
},
{
"type": "post"
"id": "161",
"name": "Angelina Jolie",
"content": "this is the actual post",
"timestamp" : "date + time",
{
"type": "comment"
"id": "162",
"name": "Ravi Tamada",
"content": "content of the comment",
"timestamp" : "time + date",
"secondary_id": "160"
}
]
}
I have 2 types of objects which i have to consider: comment and post.
Every comment is linked to a post with its secondary id. That means if secondary_id is "160" this comment belongs to the the post with the id 160. In my json there could be 50 posts then 1 comment to the 2nd post follwed by 10 more psots and then 6 various comments. Means its not orderd.
So now im trying to figure out how to safe them in my java code to get them linked. Means i need every comment for a certain post. I could do 2 arrays 1 for posts 1 for comments and then search the comments array for every comment with the id 160...161..etc... this would be pretty messy i guess.
Isnt there some pattern or smth like the key is 160 and now give me all the secondary id´s mapped as value for that key or smth?
I hope you know what i mean, kinda of hard to expain.
Basically what i would need is smth like go through the json check if its post if yes safe it. If its a comment look up the secondary id and match it to the map(or smth) of the right primary id.
First of all when serializing JSON in java there are libraries you can use, Jackson for example.
Once you familiar yourself with Jackson, I would create a base class for comment and post that has all the fields that are shared by them.
I would create a custom deserializer that after creating a comment object looking up the post object and adding the comment to the post.

Flatten and De-flatten for Solr input/output

I have lots of Java objects which have parent child relationships.
These need to be put into Solr.
To do that, we convert the Java object into json as follows:
{
"employee": {
"name" : "John",
"address": {
"apt": 100,
"city": "New York",
"country": "USA"
},
"vehicles": [
{
"name" : "Hyundai",
"color" : "red"
},
{
"name" : "Toyota",
"color" : "black"
}
]
}
}
Now since Solr does not handle this, I am flattening it out as follows:
"employee.name": "John",
"employee.address.apt": 100,
"employee.address.city": "New York",
"employee.address.country": "USA",
"employee.vehicles_0.name": "Hyundai", // Note how arrays are being flattened
"employee.vehicles_0.color": "red",
"employee.vehicles_1.name": "Toyota",
"employee.vehicles_1.color": "black",
It is easy to flatten, but clients of my library do not want the flattened schema when they query.
So I need to de-flatten the above on return from Solr and convert them back to the original Java object.
Does anyone know how this can be done?
I am thinking of somewhat crude way of taking the flattened output from Solr (as shown above) and write a parser to put the fields back to Java objects. But this seems like lot of work. An easy way out or an existing tool would be much appreciated.
I am using Solr 4.5.1
Solr is designed for search, not storing deep object graphs. You might be better off optimizing the Solr records for search and then getting the original objects from the master store by recordID or some such.
Think about what will you be trying to find. For example, will you be searching for individual vehicles? If yes, your current document level should be a vehicle not an employee.
You can index your documents in a Parent->Child structure at first place.
Take a look at this blog post: http://blog.griddynamics.com/2013/09/solr-block-join-support.html

Categories

Resources