Is there any method to convert string to map<int, dynamic>? - javascript

I make an API from Laravel and check the 'Get' request from Postman where it will return as follow:
"answer_selected": "{1:\"True\",2:\"False\"}"
Then, the Flutter application will read the JSON and serialize it using the model class.
Are there any ways to convert the value of "answer_selected" to map<int, dynamic>? Or, my JSON API response format is incorrect?

You should not return a string that is not a complete JSON. Either return
{"answer_selected": {1:"True",2:"False"}}
or
{1:"True",2:"False"}
will be much better. jsonDecode in dart supports decode to map<String, dynamic, and the key in JSON must be string too. So the JSON should like
{"1":"True","2":"False"}
If you want to transform it to map<int, dynamic>, just do
void test() {
String text = '{"1":"True","2":"False"}';
Map<String, dynamic> map = jsonDecode(text);
Map<int, dynamic> desiredMap =
map.map((key, value) => MapEntry(int.parse(key), value));
desiredMap.entries.forEach((element) {
print('${element.key} ${element.value}');
});
}

Related

Convert JavaScript Uint8Array object into Scala Object

A TypeScript application sends a Uint8Array object through an HTTP POST request to a Scala Play application.
How to convert the Uint8Array object into a Scala object in the Play application?
For example, the TypeScript code sends the following object:
{stuff: new Uint8Array([0, 1, 2])}
Inside the Scala Play controller:
case class StuffData(stuff: List[Byte])
implicit val reads: Reads[StuffData] = Json.reads[StuffData]
def processStuff = Action.async(parse.json[StuffData]) { request =>
val stuffData = request.body
println(stuffData)
}
This does not work... the error message from Play is:
For request 'POST /send-stuff'
[Json validation error List((obj.key,List(JsonValidationError(List(error.expected.jsarray),WrappedArray()))))]
By default, Unit8Array is encoded in JSON as {"0":1,"1":2,"2":3,"3":4}, so you can decode it in Scala as a Map or write your custom reader, that can translate this object into an array type. Or you could make changes from the other side, instead of using Uint8Array you can use an array or a custom stringify function that makes expected JSON.
In my opinion, the easiest one is writing the custom reader. Custom reader example:
implicit val stuffReader = new Reads[StuffData] {
def reads(js: JsValue): JsResult[StuffData] = {
JsSuccess(StuffData(
(js \ "stuff").as[Map[String, Int]].toList.map(_._2)
))
}
}

JAX-RS JSON object to JavaScript

I am new to JAX-RS and trying to build a simple website interface.
So I have written a function returning a JSON object
like this:
#GET
#Path("/mypath")
#Produces (Mediatype.APPLICATION_JSON)
public String returnJson() {
String json = //.... fill String
return json;
}
which works well when browsing to this path.
On the other hand I have a UI page like this:
#GET
Produces(MediaType.TEXT_HTML)
public InputStream viewUI() throws FileNotFoundException {
File page = new File("page.html");
return new FileInputStream(page);
}
which works also.
Next thing I want to do is filling a dropdown list in my page.html with JavaScript, which also should not be a problem.
But I dont know how to get the JSON object to the JavaScript array (in page.html).
First of all, when using jaxrs, you don't need to convert objects to json. This is done automatically by jaxrs. Your method should return an object. As you asking to convert json into array, I assume, your method should return a List. Regarding of how to call and consume results from the rest service, as per Luts Horn comment, you need to use some sort of client side library, for example jquery.
You can look here http://www.tutorialspoint.com/jquery/jquery-ajax.htm

ASP.NET WebApi DateTimeOffset serialize to Json/JavaScript (angular2)

I do not find a nice way to get a DateTimeOffset value to JavaScript (angular2).
I am using WebApi (5.2.3) and angular2. On the wire I see the date as follow:
RecordModifiedAt : "2016-03-08T17:27:11.9975483+01:00"
JavaScript/angular2 does not recognize this as valid datetime value.
I do have options, but what direction should I go:
Server side: Newtonsoft.Json, ...
Client side: angular2, ...
Others?
Many thankx for your help!
Thankx to PierreDuc feedback I have played around and I came to the following conclusion:
Since JSON does not support a Date datatype, I assume one has to make the conversion on the client side. I use the following 'pattern' (see http://codegur.com/36681078/angular-2-date-deserialization):
getTags() {
return this.http.get('/api/tag/getAll')
.map((response: Response) => this.convertData(response));
}
private convertData(response: Response) {
var data = response.json() || [];
data.forEach((d) => {
// Convert to a Date datatype
d.RecordModifiedAt = new Date(d.RecordModifiedAt);
});
return data;
}

How do I get a JavaScript array of an array of strings into a C# data structure?

I've been trying for the past hour and can't get it. At this point my controller looks like
public ActionResult GenerateMasterLink (string assetsJSON)
{
...
}
and I've confirmed that it is being passed a string like
[["Microsoft","Azure","roman_column.png"],["Microsoft","Azure","runphp.cmd"],["Microsoft","Azure","runphp.cmd"],["Microsoft","Azure","Picture1.png"],["Microsoft","Azure","vertical-align-scrnsht.png"],["Microsoft","Azure","vertical-align-scrnsht.png"]]
The only question I have is how I get the damned stuff out of it!
I've tried creating a class
public class ThreePartKey
{
public string organizationName { get; set; }
public string categoryName { get; set; }
public string fileName { get; set; }
}
and then done
ThreePartKey [] assetList = new JavaScriptSerializer().Deserialize<ThreePartKey []>(assetsJSON);
which gives me
Failed to load resource: the server responded with a status of 500
(Internal Server Error)
in my browser's console some of the time, and other times gives me
Additional information: Type
'AllyPortal.Controllers.SurfaceAssetsController+ThreePartKey' is not
supported for deserialization of an array.
as a Visual Studio error.
I've experimented with a million things and can't get this right. All I want is to have the JSON in some C# data structure where I can actually use it in my controller. Any suggestions?
You are trying to deserialize to incompatible model. You string input can be deserialized into string[][] variable but in order to allow deserializations into an ThreePartKey you need to name those values per property:
[[organizationName: "Microsoft",...]]
This will copy right value to your model
The problem is that your target datatype doesn't match the source datatype.
If you are converting an array of array of strings, you must deserialize into another array of array of strings, only them, you'll be able to convert it into whatever you want:
In short, replace
ThreePartKey [] assetList = new JavaScriptSerializer().Deserialize<ThreePartKey []>(assetsJSON);
for
ThreePartKey[] assetList = new JavaScriptSerializer().Deserialize<string[][]>(assetsJSON)
.Select(el => new ThreePartKey() {organizationName = el[0], categoryName = el[1], fileName = el[2]})
.ToArray();

OpenRasta CreatedResourceUrl use

I am sending the following response from server :
return new OperationResult.Created { CreatedResourceUrl = getURI(newDuplicateKfEntity), ResponseResource = newDuplicateKfEntity };
My question is how can I get this CreatedResourceUrl object in my javascript??
Instead of OperationResult.Created return a typed DTO and use a Codec to encode it as Json. After that consuming Json in JavaScript is simple.

Categories