How to save JSONdata into a set? - java

I have a data set. It is of the form
{
"name1": 123
"name2": 234
"name3": 345
.
.
.
}
Now, I am using a #RestController to read this through PostMan. I have a class test.java.
I have a function,
public void testController(#RequestBody String request)
I'm running this through a local host with the help of #RequestMapping. I need to save the above data set one by one in an object. The object is as follows.
public class OperatorClass implements Comparable<OperatorClass>{
private String name;
private ArrayList<String> id = new ArrayList<>();
OperatorClass(String name, String id)
{
add_id(id);
add_name(name);
}
I am trying to save this data in the following way, which by the way I have figured out is wrong.
try {
JSONObject array = new JSONObject(request);
Iterator<String> stringIterator1 = array.keys();
stringIterator1.next();
ArrayList<String> arrayList = new ArrayList<>();
OperatorClass oco = new OperatorClass(array.keys().,array.get(array.keys().toString()).toString());
System.out.println(oco.get_Name());
System.out.println(oco.get_Id());
} catch (Exception e) {
e.printStackTrace();
}
I know it is wrong because array.keys() gives all the name1, name2, name3 data. What I want to know is how to get just name 1 for this. And how to get it's following ID, to insert into a particular object.I was trying to save the object into a set of operator class.

Ok. I have got an answer to this problem. We use
String temp = stringIterator1.next();
And instead of
OperatorClass oco = new OperatorClass(array.keys().,array.get(array.keys().toString()).toString());
We use,
OperatorClass oco = new OperatorClass(temp, array.get(temp).toString);
Just remember that using string iterator will probably not display the values in the order of the data set, due to hash mapping.

Related

Converting a String to Json Object with validation in java

I am having a string like ,
name = " {
"Name" : "MyName"
}"
and having a Model class like ,
#Valid
Class Model {
#JsonProperty("Name")
#Size(min = 1)
#NotNull
private String name;
}
Now I am converting the string to Java Object by following code,
Model name = objectMapper.readValue(name, Model.class);
So the validation(min = 1 and not null) is not happening with this.
How can I validate when I am converting a string to java object?
i will try to help u.
I have an idea and it´s that u divide the process in 2 parts:
First, u take the json and put in on a JSONObject:
import org.json.JSONObject;
...
JSONObject json= new JSONObject(name);
Then, u can call, for example, a function passing a json that validate the values of json an if is correct return a model object:
public Model functionExample(JSONObject json){
try{
if(json.has("Name") && json.getString("Name")!=null){
return new Model(json.getString("Name"));
}
}catch(Exception ex){
return new Model();
}
}
This check if the field "Name" exists and it´s not null.
I don´t know if it is what u want.
I hope it help u.

How can I convert each integer/double value to String from JSON data containing nested objects and arrays?

I want to convert each integer/double value to String present in json request before storing in MongoDB database.
There can be multiple fields like amountValue in the json. I am looking for a generic way which can parse json with any number of such attributes value to string. My request will have around 200 fields.
ex: "amountValue": 200.00, to "amountValue": "200.00",
{
"templateName": "My DC Template 14",
"templateDetails": {
"beneficiaryName": "Snow2",
"dcOpenAmount": {
"amountValue": 200.00,
}
}
}
My mongoDB Document is of the form
#Document
public class TemplateDetails {
#Id
private long templateId;
private String templateName;
private Object templateDetail;
}
Because we are storing document in mongodb as an object(Which can accept any type of json request) we dont have field level control on it.
In my controller, converting the request object to json.
This is how I tried. But its not meeting my expectation. It is still keeping the amount value to its original double form.:
ObjectMapper mapper = new ObjectMapper();
try {
String json = mapper.writeValueAsString(templateRequestVO);
System.out.println("ResultingJSONstring = " + json);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
Output :
ResultingJSONstring = {"id":null,"userId":"FU.ZONKO","txnType":"LCI","accessIndicator":"Public","templateId":null,"templateName":"My DC Template 14","tags":null,"templateDetails":{"applicantDetail":{"applicantName":"Tom","applicantAddress":{"addressLine1":"Infosys, Phase 2","city":"PUNE","state":"MAHARASHTRA","country":"INDIA","zip":"40039"},"accountId":"Account1234","customerId":"JPMORGAN"},"beneficiaryName":"Snow2","dcOpenAmount":{"amountValue":200.0,"currency":"USD"}}}
Is there any way to accomplish the result ? Or anything which can help to store documents in mongodb with attribute type as String ?
You can use Json manipulation avaliable in "org.json.JSONObject" to convert Double value to Stirng .
If your Json structure won't change and will remain as said above , you can do the following.
import org.json.JSONObject;
public static void main(String args[]) {
String j = "{ \"templateName\": \"My DC Template 14\", \"templateDetails\": { \"beneficiaryName\": \"Snow2\", \"dcOpenAmount\": { \"amountValue\": 200.00 } } }";
JSONObject jo = new JSONObject(j);
jo.getJSONObject("templateDetails")
.getJSONObject("dcOpenAmount")
.put("amountValue", String.valueOf(jo.getJSONObject("templateDetails").getJSONObject("dcOpenAmount").getDouble("amountValue")));
System.out.println(jo.toString());
}
Following will be the output
{"templateDetails":{"dcOpenAmount":{"amountValue":"200.0"},"beneficiaryName":"Snow2"},"templateName":"My DC Template 14"}
I don't know for mongodb but for a json string you can replace them with a regex and the function replace like this :
public class Test {
public static void main(String[] args) {
String json = "{\"id\":null,\"userId\":\"FU.ZONKO\",\"txnType\":\"LCI\",\"accessIndicator\":\"Public\",\"templateId\":null,\"templateName\":\"My DC Template 14\",\"tags\":null,\"templateDetails\":{\"applicantDetail\":{\"applicantName\":\"Tom\",\"applicantAddress\":{\"addressLine1\":\"Infosys, Phase 2\",\"city\":\"PUNE\",\"state\":\"MAHARASHTRA\",\"country\":\"INDIA\",\"zip\":\"40039\"},\"accountId\":\"Account1234\",\"customerId\":\"JPMORGAN\"},\"beneficiaryName\":\"Snow2\",\"dcOpenAmount\":{\"amountValue\":200.0,\"currency\":\"USD\"}}}";
System.out.println(replaceNumberByStrings(json));
}
public static String replaceNumberByStrings(String str){
return str.replaceAll("(?<=:)\\d+(\\.\\d+)?(?=(,|}))","\"$0\"");
}
}
It will look for all fields with a numeric value in the json string and add quotes to the value. This way they will be interpreted as strings when the json willl be parsed.
It will not work if the value is in an array though, but in this case it should not be a problem.

How to store ArrayList into sharedPreferences in Android

In my application I want store ArrayList into sharedPreferences and get this list in another page!
For store this List i used this library : https://github.com/MrNouri/GoodPrefs
I write below codes, but when get this data I don't know how can get data!
My codes for store list :
for (int i : intList) {
stringBuilder.append("ID : ").append(testPlans.get(i).getId())
.append("Type : ").append(testPlans.get(i).getItemType())
.append("Content").append(steps.get(i).getStepData().toString()).append("-");
App.stepsBodyList.add(new DataItem(testPlans.get(i).getId(),
testPlans.get(i).getItemType(),
steps.get(i).getStepData().toString()));
}
GoodPrefs.getInstance().saveObjectsList(TEST_STEPS_STORED_LIST, App.stepsBodyList);
My codes for get data :
private List<DataItem> storedStepsBodyList = new ArrayList<>();
Toast.makeText(context, ""+
GoodPrefs.getInstance().getObjectsList(TEST_STEPS_STORED_LIST,).size()
, Toast.LENGTH_SHORT).show();
This library for get list give me 2 constructor, one is tag name and second value is default! (TEST_STEPS_STORED_LIST,)
But I don't know can i set default value for second item of constructor!
I write this GoodPrefs.getInstance().getObjectsList(TEST_STEPS_STORED_LIST,storedStepsBodyList) but show me error for this storedStepsBodyList .
How can i fix it?
Simple way, you can use Gson library, add it to build.gradle, it will serialize your list to JSON and save it to SharePreference
implementation 'com.google.code.gson:gson:2.8.6'
public void saveItems(List<Item> items) {
if (items != null && !items.isEmpty()) {
String json = new Gson().toJson(items);
mSharedPreferences.edit().putString("items", json).apply();
}
}
public List<Item> getItems() {
String json = mSharedPreferences.getString("items", "");
if (TextUtils.isEmpty(json)) return Collections.emptyList();
Type type = new TypeToken<List<Item>>() {
}.getType();
List<Item> result = new Gson().fromJson(json, type);
return result;
}

Gson converter factory retrofit2. Different types in serialization/deserialization

I'm working with wordpress post metas and rest api, i've exposed to rest a meta field called "picture_collection" wich store data as an array of integers where every number represents the ID of an attachment.
I've then modified the response when interrogating the api to give me a list of links instead of the attachment ids, like this:
function get_pic_coll ($object, $field_name, $request) {
include_once dirname(__FILE__) . '/attach_coll.php';
$pic_coll = get_post_meta ($object['id'], $field_name, true);
$json_coll = array();
if($pic_coll != null || !empty($pic_coll)){
foreach ($pic_coll as $pic){
$media_id = $pic;
$link_med = wp_get_attachment_image_src($media_id, 'medium');
$link_full = wp_get_attachment_image_src($media_id, 'full');
$medium_size = $link_med[0];
$full_size = $link_full[0];
$obj = new attach_coll($media_id, $medium_size, $full_size);
$element = $obj->return_coll_object();
$json_coll[] = $element;
}
return $json_coll;
}
}
while the attach_coll object is:
class attach_coll{
public function __construct($media_id, $medium_url, $orig_url){
$this->attach_id = $media_id;
$this->medium_size_pic = $medium_url;
$this->full_size_pic = $orig_url;
}
private $attach_id;
private $medium_size_pic;
private $full_size_pic;
public function get_media_id(){
return $this->attach_id;
}
public function get_medium_pic(){
return $this->medium_size_pic;
}
public function get_orig_pic(){
return $this->full_size_pic;
}
public function return_coll_object(){
$ret_coll = array(
"ID" => $this->get_media_id(),
"medium" => $this->get_medium_pic(),
"full" => $this->get_orig_pic()
);
return $ret_coll;
}
}
Java side the things goes like this:
1)the user make a picture and upload her, he receive in exchange the ID of the attachment that is stored inside an Integers ArrayList.
2)when he has done the program update the post_meta passing to the api the entire list.
3)the program receive the response as a json containing the whole post with my custom field, it looks like this:
{...
"id":"someValue",
"title":"myTitle",
"pic_collection":[ {'ID':'picID','mediumSizePic':'someUrl', 'FullSizePic':'SomeOtherUrl},{...}],
The php code works well as i see from the ResponseBody the json i was expecting, the problem is that i'm getting an error 'gson expected a Integer and found an Object' that is logical because the pojo is defined like:
#SerializedName("pic_collection")
private List<Integer> idList = new ArrayList<Integer>();
public void setList(List<Integer> list){
this.idList=list;
}
I tried to change my list to:
List<PicCollection> picList = new ArrayList<PicCollection>();
public class PicCollection{
#SerializedName("ID")
private int picId;
#SerializedName("medium_size")
private String medSizeUrl;
#SerializedName("full_size")
private String fullSizeUrl;
Getters and Setters
}
But that just complicated everything up and didn't resolved the problem as i'm still having a the same gson error 'ID expecting an int but found an object' and no links returned at all.
A glimpse on the code to set the id's:
iterator=idList.iterator;
while(iterator.hasNext()){
FotoCollection fc = new FotoCollection();
fc.ID = iterator.next
What can i do to resove the problem? I need a custom converter?
I just created 2 objects:
One for the request and one for the response.

How to get param value from java servlet

I'm trying to get param values passed to a Java Servlet but the string returned is not correct. I'm storing the values in a Map and checking if the key exists.
Map params;
params = request.getParameterMap();
String id = params.get("id").toString();
String data = params.get("data").toString();
System.out.println("streaming" + data + " with id of " + id);
Yet if I call this servlet via http://localhost:8080/Serv/stream/data?data=hereisdata&id=you my output looks like this:
streaming[Ljava.lang.String;#5e2091d3 with id of [Ljava.lang.String;#36314ab8
What am I missing?
EDIT: as the suggested answers are not working, I'm including the entire class as I'm likely messing something up within the class:
import java.util.*;
import javax.servlet.http.HttpServletRequest;
import Engine.Streamer;
public class AnalyzerController {
private Map params;
private String pathInfo;
private HttpServletRequest request;
public AnalyzerController(HttpServletRequest request)
{
this.params = request.getParameterMap();
this.pathInfo = request.getPathInfo();
}
public void processRequest()
{
System.out.println("procing with " + pathInfo);
switch(pathInfo){
case "/stream/data":
if(params.containsKey("id") && params.containsKey("data")) processStream();
break;
}
}
private void processStream()
{
System.out.println("we are told to stream");
String data = request.getParameter("data");
String id = request.getParameter("id");
Streamer stream = new Streamer();
stream.streamInput(data, "Analyzer", id);
}
}
This line specifically is throwing the NPE: String data = request.getParameter("data");
If you look at the docs of the Request#getParameterMap(), it returns a Map of the type Map<String, String[]>. Therefore, you need to take out the first element from the value String[] array returned from the map.
String id = params.get("id")[0];
Ofcourse, you can avoid all this and directly get the parameters from the request objects using the Request#getParameter() method.
String id = request.getParameter("id");
Edit: Looking at your class code, it seems that the instance variable request is not initialized. Initialize that in the constructor like this:
public AnalyzerController(HttpServletRequest request)
{
this.request = request; // Initialize your instance variable request which is used in the other methods.
this.params = request.getParameterMap();
this.pathInfo = request.getPathInfo();
}
You can get the required parameters instead of the whole map
String id = request.getParameter("id");
String data = request.getParameter("data");
Try something like this.
String data = ((String)params.get("data"));
Or directly from the Request.
String data = request.getParameter("data");
You can use request object plus it's method for to get data usinggetParameter() of you can use getParameterValues() if multiple data are from page.
String id = request.getParameter("id")
String data = request.getParameter("data")
why are you using Map ?
Any special need of it or any reason ?
or you can use like this :
String id = params.get("id")[0];

Categories

Resources