Use of Object Mapper in Java [closed] - java

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
I am writing code for restaurant class the produces JSON in the given format during serialization
What are the best prectices to convert a json string using object Mapper
Restaurant restaurant = new Restaurant();
restaurant = new ObjectMapper().readValue(jsonString, Restaurant.class);

First line creates a new Restaurant object. second line also creates a new Restaurant object but using a JSON string, you need Jackson library for this task. You don't need first line if your requirement is only to create an object.
lets say your Restaurant class looks like this.
class Restaurant {
private String id;
private String name;
//getters and setters
}
and you have a JSON look likes this.
String json = "{ \"id\" : \"1\", \"name\" : \"My Restaurant\" }";
Then you can create Restaurant object using second line
Restaurant restaurant = objectMapper.readValue(json, Restaurant.class);
after that you can read json values from restaurant object.
System.out.println(restaurant.getName());
output:
My Restaurant

The ObjectMapper will parse the JSON in jsonString to a Restaurant object (that's why you give it Restaurant.class as a parameter). It will then store the created object in the restaurant variable.

Related

how can i pass an array of objects in query params in postman for the post request? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 months ago.
Improve this question
Below is the code snippet where i need to pass the change_task objects in the query params for the POST request. how can i achieve this without adding it in the body ?
"change_task": [
{
"change_task_type": "Validation",
"planned_start_date": "2022-09-29T20:30:00",
"assignment_group": "CSRT_L2_Support",
"planned_end_date": "2022-09-30T02:30:00",
"short_description": "Test validation",
"description": "test Validation task"
},
{
"change_task_type": "Implementation",
"planned_start_date": "2022-09-29T20:30:00",
"assignment_group": "CSRT_L2_Support",
"planned_end_date": "2022-09-30T02:30:00",
"short_description": "test implementation",
"description": "test implementation task"
}
]
First of all you may ask why i should pass array of attributes with in query param, instead the content body (request body) is used for the data that is to be uploaded/downloaded to/from the server and the query parameters are used to specify the exact data requested.
So theoretically the request body should contain the data you are posting or patching and the query string, as part of the URL (a URI), it's there to identify which resource you are posting or patching.
Regarding to your specification and shared data perhaps its better to use content body instead of query string, this article may help as well.
But if yet you instead to use as query string you must know the answer is depends in framework-specific, see specific answers in here.

How to validate keys of a json in java [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 9 months ago.
Improve this question
Let's assume valid json is
{
"a": "valueA",
"b": "valueB"
}
Is there a neat way in java to validate the keys of json so that if the following is processed it fails with a message stating a particular key(in this case 'a1') is not a supported key/wrong key
{
"a1": "valueA", //wrong key a1 instead of a
"b": "valueB"
}
You have to map this json to any java class something like:
class Foo{
String a;
String b;
}
& then calling :
Foo foo=new ObjectMapper().readValue("{ \"a1\" : \"valueA\", \"b\" : \"valueB\"}",Foo.class);
will give you exception as
Unrecognized field "a1"

Firebase Android - create node from keys in an Arraylist [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
I have an ArrayList full of specific keys. How would I go about making a new node with just the keys in the Arraylist?
Assuming you have an ArrayList that look like this:
List<String> list = new ArrayList<>();
To create a new node using only the keys, please use the folliwing code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
for(String s : list) {
rootRef.child("yourNode").child(s).setValue(true);
}
And your database structure will look like this:
Firebase-root
|
--- yourNode
|
--- arraListKey1: true
|
--- arraListKey2: true
|
--- //and so on
Could you elaborate more? What have you managed to do so far? If for example i have an arraylist of strings containing two items, item1 and item2, then i can loop through the arraylist and pushing the string to your firebase server as the key. For example
ArrayList<String> myArray= new ArrayList<>();
myArray.add(item1);
myArray.add(item2);
for (int i =0; i<myArray.size();i++){
String key = myArray.get(i) ;
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference ref = database.getReference();
ref.child(key);
ref.child(key).child("itemUnderThisKey").setValue("value you want to set")
}
This is how ur firebase structure will look like :
Best thing is to understand the firebase data structures and you can make them suite your whatever needs. Hope the above will help.

java 8 stream transform list of maps to one single map. Cannot be cast to integer exception [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
The following code is a java 8 stream expected to transform list of maps to one map containing all the elements from this list of maps.. The test data below is throwing a cannot be cast to integer exception.
Map test = new HashMap();
test.put("PreLoadTransactionId", 1234);
List<Map<String, String>> preloadTranactions = new List<>();
preloadTranactions.add(test);
final Map<String, Date> preloadTranactionIdUpdateMap = preloadTranactions.stream()
.collect(Collectors.toMap(
preloadTransaction -> preloadTransaction.get("PreLoadTransactionId"),
preloadTransaction -> new Date(preloadTransaction.get("UpdateDate")),
(preloadTranaction1, preloadTranaction1Dup) -> preloadTranaction1));
Expecting to transform a list maps into a Map containing all the elements from this list of maps. Instead getting exception: "java.lang.Integer cannot be cast to java.lang.String"
How am I getting this exception ???
First of all we do not know from this code snippet what is the type of "PreLoadTransactionId" and "UpdateDate" fields in the map.
If any of them is Integer you will get this error.
You should check how the map of preloadTransactions is being populated.
This when it is defined like Map<String, String> doesn't mean anything since in the example here:
List<Map<String, String>> preloadTranactions = new ArrayList<>();
Map test = new HashMap();
test.put("PreLoadTransactionId", 1234);
preloadTranactions.add(test);
You could save integer as a transactionId even it is declared in preloadTranactions as a Map with String values
So I think you just need to see how the map is populated and to fix the population or to explicitly cast to String in your Collector like this:
preloadTranactions.stream()
.collect(Collectors.toMap(
preloadTransaction ->
String.valueOf( //THIS WILL FIX THE ISSUE EVEN IF VALUE IS NUMBER
preloadTransaction.get("PreLoadTransactionId")
),
preloadTransaction -> new Date(preloadTransaction.get("UpdateDate")),
(preloadTranaction1, preloadTranaction1Dup) -> preloadTranaction1));

How to return arraylist using restful webservices in java? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I want to return values in the json format. I am using (MediaType.APPLICATION_JSON) for to return the values. How to return the ArrayList using this?
Example:
[
{
"node_title": "Ambivalence About Government Will Be Topic at next Lecture ",
"nid": "Topic - Get the Government Off of Our Backs – There Ought to Be a Law: Reconciling Our National Ambivalence About Government."
},
{
"node_title": "Recycling initiative gains steam under new director",
"nid": "University administrators listened and hired a sustainability coordinator whose main focus has been to heighten recycling efforts and awareness."
},
{
"node_title": "Special Week to Combat Hate and Discrimination",
"nid": "For the seventh year, University students will observe “Why Do You Hate Me?” Week, which will run from March 28th through April 2nd."
},
{
"node_title": "AUSP joins Nursing School on mission trip to Caribbean",
"nid": "The School of Audiology and Speech-Language Pathology during spring break went to Dominican Republic to provide much-needed assistance to a school for deaf and impoverished children."
}
]
Please guide me.
If you want to parse this into java code, you can do something like this:
First, get Gson, a google library to work with JSON.
Next, define a class like:
class Node {
String node_title;
String nid;
}
Then you can do
Type collectionType = new TypeToken<List<Node>>(){}.getType();
List<Node> details = gson.fromJson(myJsonString, collectionType);

Categories