I have a post message. I use akka-http.
And I have to call this route from an another server.
So I have to add cors with HttpOriginRange.* with ch.megard.akka.http.cors.CorsDirectives.
The answer is a json.
And I want to have a ContentType application/json
How can I do that?
Here is my route code :
settings = CorsSettings.defaultSettings.copy(allowGenericHttpRequests = true, allowCredentials = false, allowedOrigins = HttpOriginRange.*)
val route: Route =
handleRejections(CorsDirectives.corsRejectionHandler) {
cors(settings) {
handleRejections(RejectionHandler.default) {
post {
authenticated(doAuthApp) { app =>
complete("success")
}
}
}
}
}
I tried this :
val route: Route =
handleRejections(CorsDirectives.corsRejectionHandler) {
cors(WebServer.settings) {
handleRejections(RejectionHandler.default) {
(decodeRequest & encodeResponse) {
mapResponseEntity(_.withContentType(ContentTypes.`application/json`)) {
post {
authenticated(doAuthApp) { app =>
complete("success")
}
}
}
}
}
}
}
If I do that I have an error : Unexpected 's'
Could you help me please?
If you try
var settings = CorsSettings.defaultSettings.copy(allowGenericHttpRequests = true, allowCredentials = false, allowedOrigins = HttpOriginRange.*)
val route =
pathPrefix("testEndpoint") {
handleRejections(CorsDirectives.corsRejectionHandler) {
cors(settings) {
handleRejections(RejectionHandler.default) {
post {
entity(as[String]) {
app =>
complete("success")
}
}
}
}
}
}
Related
There is a way to map json objects in react-native? For example, let's say I receive the following object:
{
"dados": {
"ultimaAtualizacao": {
"nome": "Lala"
}
"nascimento": "01/01/2001"
}
}
I want to map it like this:
{
"data": {
"lastUpdate": {
"name": "Lala"
}
"dob": "01/01/2001"
}
}
Considering that fetch returns the first object, this would be possible doing the following code:
myService.get(url).then(response => this.mapObject(response, []));
//Considering state is initialized and I have the mapedEntity to return correct properties
mapObject(jsonObject, parentProperty) {
for (let property in jsonObject) {
if (Array.isArray(jsonObject[property])) {
this.mapArray(jsonObject[property], [...parentProperty,property]); //Would be something like mapObject function
} else if (typeof jsonObject[property] === 'object') {
this.mapObject(jsonObject[property],[...parentProperty,property]);
} else {
let prop = this.state;
for(let k of parentProperty) {
prop = prop[mapedEntity[k]];
}
prop[entidadeMapeada[property]] = jsonObject[property];
}
}
}
There is someway simplier to achieve this?
I am trying to parse below JSON data and I get the data from remote server. I do a HTTP get to pull this data. I get "java.lang.IllegalStateException:Not a JSON Object: [{.."
I use gson to parse the data and get the fields.("endPointName")
Code:
public void getDevices() throws Exception{
// createHttpClient();
ContentExchange contentExchange = new ContentExchange(true);
contentExchange.setMethod("GET");
contentExchange.setURL("http://10.37.14.XX:8080/api/clients");
// contentExchange
httpClient.send(contentExchange);
if (contentExchange.waitForDone() == HttpExchange.STATUS_COMPLETED) {
System.out.println("##Sucesss");
int status = contentExchange.getStatus();
System.out.println(contentExchange.getResponseFields().getStringField("Content-Type"));
String responseContent = contentExchange.getResponseContent();
getAEDetails_gson(responseContent);
}else{
System.out.println("##failed");
}
}
private void getAEDetails_gson(String responseContent) throws Exception {
JsonElement jelement = new JsonParser().parse(responseContent);
JsonObject rootobj = jelement.getAsJsonObject();
JsonArray paymentsArray = rootobj.getAsJsonArray();
for (JsonElement pa : paymentsArray) {
JsonObject paymentObj = pa.getAsJsonObject();
String quoteid = paymentObj.get("endpoint").getAsString();
System.out.println("name is " + quoteid);
}
}
Sample Json(response content)
[
{
"endpoint":"testclient",
"registrationId":"H9eTBcZbGf",
"registrationDate":"2017-01-20T00:00:17-05:00",
"lastUpdate":"2017-01-20T00:00:17-05:00",
"address":"10.37.3.24:56730",
"lwM2mVersion":"1.0",
"lifetime":300,
"bindingMode":"U",
"rootPath":"/",
"objectLinks":[
{
"url":"/",
"attributes":{
"rt":"123",
"ct":1543
}
},
{
"url":"/1/0",
"attributes":{
}
},
{
"url":"/1024/12",
"attributes":{
}
}
],
"secure":false,
"additionalRegistrationAttributes":{
}
},
{
"endpoint":"test2",
"registrationId":"1xqmsOx2QH",
"registrationDate":"2017-01-20T00:00:54-05:00",
"lastUpdate":"2017-01-20T00:00:54-05:00",
"address":"10.37.3.24:56830",
"lwM2mVersion":"1.0",
"lifetime":300,
"bindingMode":"U",
"rootPath":"/",
"objectLinks":[
{
"url":"/",
"attributes":{
"rt":"oma.lwm2m",
"ct":1543
}
},
{
"url":"/1/0",
"attributes":{
}
},
{
"url":"/1024/12",
"attributes":{
}
}
],
"secure":false,
"additionalRegistrationAttributes":{
}
}
]
Okay so.... I have this:
def convertPost = extract {
_.request.entity.asString.parseJson.convertTo[CustomClass]
}
private def myRoute: Route =
(post & terminalPath("routeness")) {
convertPost { req =>
detach() {
ThingHandler.getMyResults( req )
}
}
}
but I want to template it, like this:
def convertPost[T] = extract {
_.request.entity.asString.parseJson.convertTo[T]
}
private def myRoute: Route =
(post & terminalPath("routeness")) {
convertPost[CustomClass] { req =>
detach() {
ThingHandler.getMyResults( req )
}
}
}
But that doesn't work. I am using spray-json-shapeless. My error is
Error:(28, 50) Cannot find JsonReader or JsonFormat type class for T
_.request.entity.asString.parseJson.convertTo[T]
^
when I try:
def getStuff[T] = extract {
_.request.entity.asInstanceOf[T] // .convertTo[T]
}
it gives:
spray.http.HttpEntity$NonEmpty cannot be cast to com.stuff.CustomClass
I want to search in json data with multiple levels of array. My search list return names of my objects but just from the first level. How could i do return all my object's names regardless their levels ?
In this example : OST, OST details, Apocalpse Now, Arizona Dream, Dexter
Data
<script type="application/json" id="dataMusic">
{
"name":"Music",
"level":"1",
"size":36184,
"children":[
{
"name":"OST",
"level":"2",
"size":1416,
"children":[
{
"name":"OST details",
"level":"3",
"size":1416,
"children":[
{
"name":"Apocalypse Now",
"size":15
},
{
"name":"Arizona Dream",
"size":19
},
{
"name":"Dexter",
"size":20
}
]
}
]
}
]
}
</script>
Function
var dataMusic = document.getElementById('dataMusic').innerHTML;
var dataTree = JSON.parse(dataMusic);
var optArray = [];
for (var i = 0; i < dataTree.children.length - 1; i++) {
optArray.push(dataTree.children[i].name);
}
optArray = optArray.sort();
I try this method Parsing Nested Objects in a Json using JS without success
Function
var optArray = [], Music, OST, OST details;
for (Music in dataTree) {
for (OST in dataTree[Music]) {
for (OST details in dataTree[Music][OST]) {
if (OST details in optArray) {
optArray[OST details].push(dataTree[Music][OST][OST details].name)
} else {
optArray[OST details] = [dataTree[Music][OST][OST details].name]
}
}
}
}
You must use nested loops
for Music.children.length
for OST.children.length
for OST details.children.length
Edit : Function
var optArray = [], Music, OST, OST_details;
for (Music in dataTree) {
for (OST in dataTree[Music]) {
for (OST_details in dataTree[Music][OST]) {
if (OST_details in optArray) {
optArray[OST_details].push(dataTree[Music][OST][OST_details].name)
} else {
optArray[OST_details] = [dataTree[Music][OST][OST_details].name]
}
}
}
}
I got it
var dataMusic = document.getElementById('dataMusic').innerHTML;
var dataTree = JSON.parse(dataMusic);
var result = [];
function getAll( input, target ) {
function parseData( input, target ) {
$.each( input, function ( index, obj ) {
if ( index == target ) {
result.push( obj );
}
else {
switch ( $.type( obj ).toLowerCase() ) {
case "object":
case "array":
parseData( obj, target );
break;
}
}
});
}
parseData( dataTree, "name" );
result = result.sort();
return result;
}
alert(JSON.stringify( getAll( dataTree, "name" )));
Thanks to this post :
Parsing multi-level json ; Demo
my json structure is:
{
"bob": {"blue": 2 }
}
next i did this for checking does not exists properties:
if(myArray['alice']['red] === false) {
console.log('undefined');
}
then it returns "Cannot read property 'red' of undefined"
try this code:
var arr = {
"bob": {"blue": 2 }
}
if(!arr['alice']) {
console.log('undefined');
}
else if (!arr['alice']['red']) {
console.log('undefined');
}