Call java generics on nativescript to convert JSON to HashMap - java

I'm building an Nativesctipt app for Android that uses Firebase as backend and I'm using the native Firebase Android library v2.4.0
I can insert objects in Firebase just fine using the following {N} Javascript syntax
var user = new java.util.HashMap();
user.put("name", viewModel.get("name"));
user.put("lastName", viewModel.get("lastName");
var address = new java.util.HashMap();
address.put("address", viewModel.get("address");
address.put("number", viewModel.get("number");
address.put("city", viewModel.get("city");
user.put("address", address);
ref = new Firebase("https://my-firebase-app-url/users");
refUser = ref.child(viewModel.get("username"));
refUser.setValue(user);
The problem with this is that I have to manually convert every javascript object into a java hashSet (and back) and I wanted to do it using a JSON to HashMap library so I have imported the java Jackson library into my {N} app.
According to this site here's the way to convert a JSON to a HashMap in Java using Jackson:
ObjectMapper mapper = new ObjectMapper();
String json = "{\"name\":\"mkyong\", \"age\":29}";
Map<String, Object> map = new HashMap<String, Object>();
// convert JSON string to Map
map = mapper.readValue(json, new TypeReference<Map<String, String>>(){});
I'm looking for a way to translate that into a {N} Javascript code that will do it for me but I'm unable to use generics notation in {N} Javascript. Does anybody know how I could do it? I have tried some ways but all of them crashed the application. Here's an {N} Javascript snippet does not work:
var ObjectMapper = com.fasterxml.jackson.databind.ObjectMapper;
var TypeReference = com.fasterxml.jackson.core.type.TypeReference;
var mapper = new ObjectMapper();
var map = mapper.readValue(JSON.stringify(user), new TypeReference());
refUser.setValue(map);
Any help is greatly appreciated.

Related

How to map Json (from procedure) to Java object

I have the following SP (SQL server) that return a Json output.
BEGIN
SET #jsonOutput = (
SELECT
Program.Name AS ProgramName,
ProgramOwner.FirstName AS OwnerFirstName,
FROM ProgramOwner, Program
WHERE Program.Id = ProgramOwner.ProgramOwner2Program
FOR JSON PATH,WITHOUT_ARRAY_WRAPPER)
I would like to map the return Json output to a List of ProgramDto via modelMapper. Not sure hot to do that since the return values from call.execute is an Object.
Something like this:
SimpleJdbcCall call = new
SimpleJdbcCall(jdbcTemplate).withProcedureName(programProc).declareParameters(
new SqlOutParameter("jsonOutput", Types.VARCHAR));
Map<String,Object>out = call.execute(new MapSqlParameterSource());
if(out.size()>0) {
// Only to show what I am trying to do
Type rootType = new TypeToken<List<ProgramDto>>() {}.getType();
modelMapper.map(out.get("jsonOutput"),rootType );
}
Thank you
As I understood you are trying to get a list of object from
You can use Jackson api
Like this
say for example your json is in variable named jsonData, then you can get the object you need like below.
ObjectMapper mapper = new ObjectMapper();
List<Type> myList = Arrays.asList(mapper.readValue(jsonData, Type[].class));
You can also find more examples here

What is the best way to pass multiply parameters as one http query parameter?

I have java web application (servlet) that does user authentication using SalesForce Server OAuth Authentication Flow. This OAuth Authentication provides "state" query parameter to pass any data on callback. I have a bunch of parameters that I want to pass through this "state" query param. What is the best way to do it? In java in particularly?
Or in other words, what is the best way to pass an array or map as a single http query parameter?
You can put all in json or xml format or any other format and then encode in base64 as a one large string. Take care that params can impose some hard limit on some browser/web server.
So, I have done it this way. Thank you guys! Here are some code snippets to illustrate how it works for me:
// forming state query parameter
Map<String, String> stateMap = new HashMap<String, String>();
stateMap.put("1", "111");
stateMap.put("2", "222");
stateMap.put("3", "333");
JSONObject jsonObject = new JSONObject(stateMap);
String stateJSON = jsonObject.toString();
System.out.println("stateJSON: " + stateJSON);
String stateQueryParam = Base64.encodeBase64String(stateJSON.getBytes());
System.out.println("stateQueryParam: " + stateQueryParam);
// getting map from state query param
ObjectMapper objectMapper = new ObjectMapper();
stateMap = objectMapper.readValue(Base64.decodeBase64(stateQueryParam.getBytes()), LinkedHashMap.class);
System.out.println("stateMap: " + stateMap);
Here is output:
stateJSON: {"1":"111","2":"222","3":"333"}
stateQueryParam: eyIxIjoiMTExIiwiMiI6IjIyMiIsIjMiOiIzMzMifQ==
stateMap: {1=111, 2=222, 3=333}

Convert object to JSON without escapings on strings

I have searched the web for answer and everywhere is done like this:
JSONObject params = new JSONObject();
Gson gson = new Gson();
params.put("Event", gson.toJson(myEvent));
But this is returning me Json like this with all escapings on ":
"Event":"{\"Test1\":\"TestValue1\",\"TestObj\":{\"Test2\":\"TestValue2\",\"Test3\":\"TestValue3\"...
How can I have Json free of all escapings, just like this:
"Event":"{"Test1":"testValue1","TestObj":{"Test2":"testValue2","Test3":"testValue3"...
Cheers mates.
I can pass the object like this, property by property:
createEvent.put("Test1", myObj1.Test1);
createEvent.put("Test2", myObj2.Test2);
and pass the Json to api, but Notes is with escapings:
String myNoteListJson = new Gson().toJson(myNoteList);
createEvent.put("Notes", myNoteListJson);
I found an answer, here it is:
I am passing property by property:
createEvent.put("Test1", myObj1.Test1);
createEvent.put("Test2", myObj2.Test2);
and the Notelist problem is solved like this:
JSONArray mJSONArray = new JSONArray(myNoteList);
createEvent.put("Notes", mJSONArray);

how to manipulate HTTP json response data in Java

HttpGet getRequest=new HttpGet("/rest/auth/1/session/");
getRequest.setHeaders(headers);
httpResponse = httpclient.execute(target,getRequest);
entity = httpResponse.getEntity();
System.out.println(EntityUtils.toString(entity));
Output as follows in json format
----------------------------------------
{"session":{"name":"JSESSIONID","value":"5F736EF0A08ACFD7020E482B89910589"},"loginInfo":{"loginCount":50,"previousLoginTime":"2014-11-29T14:54:10.424+0530"}}
----------------------------------------
What I want to know is how to you can manipulate this data using Java without writing it to a file?
I want to print name, value in my code
Jackson library is preferred but any would do.
thanks in advance
You may use this JSON library to parse your json string into JSONObject and read value from that object as show below :
JSONObject json = new JSONObject(EntityUtils.toString(entity));
JSONObject sessionObj = json.getJSONObject("session");
System.out.println(sessionObj.getString("name"));
You need to read upto that object from where you want to read value. Here you want the value of name parameter which is inside that session object, so you first get the value of session as JSONObject using getJSONObject(KeyString) and read name value from that object using function getString(KeyString) as show above.
May this will help you.
Here's two ways to do it without a library.
NEW (better) Answer:
findInLine might work even better. (scannerName.findInLine(pattern);)
Maybe something like:
s.findInLine("{"session":{"name":"(\\w+)","value":"(\\w+)"},"loginInfo":{"loginCount":(\\d+),"previousLoginTime":"(\\w+)"}}");
w matches word characters (letters, digits, and underscore), d matches digits, and the + makes it match more than once (so it doesnt stop after just one character).
Read about patterns here https://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html
OLD Answer:
I'm pretty sure you could use a scanner with a custom delimiter here.
Scanner s = new Scanner(input).useDelimiter("\"");
Should return something like:
{
session
:{
name
:
JSESSIONID
,
value
:
5F736EF0A08ACFD7020E482B89910589
And so on. Then just sort through that list/use a smarter delimiter/remove the unnecessary bits.
Getting rid of every other item is a pretty decent start.
https://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html has info on this.
I higly recomend http-request built on apache http api.
private static final HttpRequest<Map<String, Map<String, String>>> HTTP_REQUEST = HttpRequestBuilder.createGet(yourUri, new TypeReference<Map<String, Map<String, String>>>{})
.addDefaultHeaders(headers)
.build();
public void send(){
ResponseHandler<Map<String, Map<String, String>>> responseHandler = HTTP_REQUEST.execute();
Map<String, Map<String, String>> data = responseHandler.get();
}
If you want use jackson you can:
entity = httpResponse.getEntity();
ObjectMapper mapper = new ObjectMapper();
Map<String, Map<String, String>> data = mapper.readValue(entity.getContent(), new TypeReference<Map<String, Map<String, String>>>{});

Serialize Pojos to JSON using new standard javax.json

I like the idea of having a standard for JSON serialization in Java, javax.json is a great step forward you can do an object graph like this:
JsonObject jsonObject3 =
Json.createObjectBuilder()
.add("name", "Ersin")
.add("surname", "Çetinkaya")
.add("age", 25)
.add("address",
Json.createObjectBuilder()
.add("city", "Bursa")
.add("country", "Türkiye")
.add("zipCode", "33444"))
.add("phones",
Json.createArrayBuilder()
.add("234234242")
.add("345345354"))
.build();
That's it, but how can I serialize a pojo or simple Java object(like a Map) direct to JSON?, something like I do in Gson:
Person person = new Person();
String jsonStr = new Gson().toJson(person);
How can I do this with the new standard API?
Java API for JSON Processing (JSR-353) does not cover object binding. This will be covered in a separate JSR.
See JSR-367, Java API for JSON Binding (JSON-B), a headline feature in Java™ EE 8.
Document: Json Binding 1.0 Users Guide
// Create Jsonb and serialize
Jsonb jsonb = JsonbBuilder.create();
String result = jsonb.toJson(dog);
// Deserialize back
dog = jsonb.fromJson("{name:\"Falco\", age:4, bitable:false}", Dog.class);
Maybe it's because this question is almost 5 years old (I didn't check which java release has these classes) but there is a standard way with javax.json.* classes:
JsonObject json = Json.createObjectBuilder()
.add("key", "value")
.build();
try(JsonWriter writer = Json.createWriter(outputStream)) {
writer.write(json);
}

Categories