How can I use JSON.stringify with a Typescript Map. The presumption is the Map keys are all strings.
In this example, the console output is an empty {}
const myMap = new Map<string, Employee>();
myMap.set('employee1', new Employee());
myMap.set('employee2', new Employee());
myMap.set('employee3', new Employee());
console.log('myMap', JSON.stringify(myMap));
this way you can stringify the Map value
JSON.stringify([...myMap])
and if you want to convert the value back to Map
let obj = JSON.parse(stringifyValue)
let myMap = new Map();
for (let k of Object.keys(obj)) {
myMap.set(k, obj[k]);
}
check this Converting ES6 Maps to and from JSON
Related
I just start to learn more about dart and flutter and followed some tutorials. Now I have a start with a Google maps app and what i want to do is to import my own polylines.
Normally the polylines are generated automatically between the start and destination point but i want to change that:
This is the automatic standard:
List<LatLng> polylineCoordinates = [];
This is how I can manually change that.
List<LatLng> polylineCoordinates = [
LatLng (4.6546609, 52.2997741),
LatLng (4.6539206, 52.2998594),
LatLng (4.6522898, 52.3002268),
LatLng (4.651689, 52.3002793),
];
Now I dont want to manually add it in the code but I want to fill it from a file(json, csv)
What is best to do and how can I start.. Hope someone can help me.
Your question is more like "how to read data from json/csv into dart code".
Anyway, here's a standard way to do it:
Assuming that you have the values in a json file like the following:
{
[
{ 'lat':33.22222,
'long':20.25451
},
{ 'lat':30.89222,
'long':20.55551
}
]
}
Declare the json file in the pubspec.yaml
flutter:
assets:
- assets/sample.json
Write a function that parses the json
readJson() async {
final String assetFile = await rootBundle.loadString('assets/sample.json');
final data = await json.decode(assetFile);
return data;
}
Use that data for your desired logic
List<LatLng> polylineCoordinates = readJson().map((e)=>LatLng(e['lat'], e['long']).toList;
I want get json file on ftp server and convert this in map to use the objects.
I can do this.
Map myMap = new Map();
http
.get('link.com')
.then((response) =>{
myMap = json.decode(Utf8Decoder().convert(response.bodyBytes))})
.whenComplete(() => {
myMap.forEach((key, value) {
setState(() {
print(value);
});
})
});
But I want to write the map to a file in my application folder and read the locally stored file.
but when I'm trying with my model file I can't because I have
{name: [{title: title, content: content}]}
and not
"name": [{"title": "title","content":"content"}]}
So I can't create a Map from the string.
How can I solve this?
Instead of saving the file using myMap.toString() use json.encode to encode the map to a valid json string and save that that way you can decode it again when reading the file.
I need to output some JSON file to client app. So, I have following code
var content = System.IO.File.ReadAllText(this.path);
var model = JsonConvert.DeserializeObject(content, new JsonSerializerSettings() {
ContractResolver = new CamelCasePropertyNamesContractResolver()
});
return Ok(model);
it should be returned as Object with camelCase property names, but I get it the same as it is in JSON file (PascalCase)
to be mentioned, in the Startup file, IMvcBuilder.AddJsonOptions also sets
services.AddMvc()
.AddJsonOptions(options => {
options.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
options.SerializerSettings.DateTimeZoneHandling = DateTimeZoneHandling.Local;
});
and it works perfectly, other controllers returns objects as expected. The problem is only with object converted from JSON file.
How can I fix that?
Ok, I've found a way to fix it with
var model = JsonConvert.DeserializeObject<JObject>(content);
and now it works as expected :|
How do I get the binary data of the buffer in C#?
item = {[_buffer, JVBERi0xLjMKJeLjz9MKMiAwIG9iago8PAovQ3JlYXRpb25EYXR]}
I tried this but get an error:
HttpResponseMessage response = await client.GetAsync(url);
if (response.IsSuccessStatusCode)
{
var dataStream = response.Content.ReadAsStringAsync().Result;
var parsed = JObject.Parse(dataStream);
if (dataStream == null)
return HttpNotFound();
foreach (dynamic item in parsed)
{
// If user decides to save the file, this will help...
Response.AddHeader("content-disposition", "filename=" + Path.GetFileName(fileDoc));
return File(item._buffer, "application/pdf");
}
}
Assuming your raw JSON looks something like this:
{
"_buffer": "JVBERi0xLjMKJeLjz9MKMiAwIG9iago8PAovQ3JlYXRpb25EYXRlIChEOjIwMTgwMTI2MjI0ODI1LTA1JzAwJykKL01vZERhdGUgKEQ6MjAxODAxMjYyMjQ4MjUtMDUnMDAnKQovUHJvZHVjZXIgKEJDTCBlYXN5UERGIDcuMDAgXCgwMzU1XCkpCi9DcmVhdG9yIChlYXN5UERGIFNESyA3IDcuMCkKPj4KZW5kb2JqCgo4"
}
Then the value of the "_buffer" property would appear to be Base64 encoded binary. As documented in its serialization guide Json.NET supports automatically deserializing Base64 strings to byte []. Thus you can do:
var _buffer = JsonConvert.DeserializeAnonymousType(dataStream, new { _buffer = (byte[])null })._buffer;
Then pass the returned byte array to Controller.File(Byte[], String).
By using JsonConvert.DeserializeAnonymousType() you avoid the need to load your (possibly large) response into an intermediate JToken hierarchy, and also avoid the need to create an explicit, concrete type just to deserialize a single byte [] property.
I am using phonegap here.But how to read JSON file ??
function readAsText(file) {
var reader = new FileReader();
alert("inside readAstext");
var jsonArray;
reader.onloadend = function(evt) {
displayContents = evt.target.result;
alert("assigned");alert(displayContents);
jsonArray = JSON.parse(displayContents);
}
reader.readAsText(file);
handleResponse(true,jsonArray);
}
here evt.target.result is displaying my file in alert as a sting . But once i parse that file I am getting [object object] once inside for loop. How to parse this ? Am i wrong?how to read each content of json here?
When you parse a JSON file, you convert it onto an objects, hence your 'alert' is correct. Now that you have an object, simply retrieve the values from the object's properties.