Creating a dynamic JSON from C# to JavaScript - javascript

I am new at C# programming and I am developing an application based on geolocation for my Graduate.
I have a Javascript which is responsible for creating the map and inserting the markers. But the markers are inserted from a JSON file, like this:
{
"Id": 1,
"Latitude": -19.212355602107472,
"Longitude": -44.20234468749999,
"Descricao": "Conteúdo do InfoBox 1"
},
And after that. they call this file by this:
function carregarPontos() {
$.getJSON('js/pontos.json', function(pontos) {
$.each(pontos, function(index, ponto) {
var marker = new google.maps.Marker({
position: new google.maps.LatLng(ponto.Latitude, ponto.Longitude),
title: "Meu ponto personalizado! :-D",
map: map
});
});
});
}
carregarPontos();
My problem is I need to have those points from MySql DB.
I created a DataTable where I have the information I need to pass to this JSON, but I don't have any clues regarding how to make it.
Any help? Please keep in mind I am a noob at C# and JSON programming.

While the standard C# library offers some JSON support, you're better off using the free JSON.Net library from Newtonsoft. You can add it to your project in Visual Studio through the NuGet package manager (Project > Manage NuGet packages).
Then make sure your file has:
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
To parse a JSON, just write dynamic json = JObject.Parse(str);
Then you can access its properties just like you would in JavaScript, the only difference being that undefined properties will return null.
dynamic json = JObject.Parse("{example: \"Hello world\"}");
Console.Write(json.example); // prints "Hello world"
To write a JSON, just create a JObject and then append strings, numbers, JArrays and JObjects to it.
dynamic json = new JObject();
json.example = "Hello world";
json.myArray = new JArray(1, 2, 3, 4);
Console.Write(json);
// {
// "example": "Hello world",
// "myArray": [
// 1,
// 2,
// 3,
// 4
// ]
// }

as far as I understand you have some data stored in your sql database from where you will fetch the data and pass to a javascript function.
If that is the case then you can refer to this link.
Pass json/javascript data/objects to c# function using ajax
The example given is using aspx approach and not the MVC but it will be similar.

Related

How i send a object from Java like a Javascript object?

I have an application Angular 7 frontend, Android mobile and a Laravel backend. I send an object in Angular 7 that is working fine on Laravel this is the object
{
"mov_entry_id": 72507,
"limitHour": "02/07/2019 13:40:27",
"plate": null,
"mov_vehicle_id": 1,
"mov_vehicle_name": "Carro",
"value": "8.00",
"mov_area_id": 7,
"mov_area_name": "AB",
"mov_user_id": 1,
"validated": "N",
"updated_at": "02/07/2019 13:20:27",
"mov_entry_ean13": "7800000725070",
"created_at": "02/07/2019 13:20:27"
}
I'm sending a post method from angular to laravel this is the backend part that receive this object
$entryObj = $request->input('entry');
$userid = $request->input('userid');
$hourValue = 0;
$validatedDate;
$response["success"] = 1;
$response["message"] = "Entrada validada com blabla";
$response['entryObj'] = $entryObj;
$response['mov_entry_ean13'] = $entryObj["mov_entry_ean13"];
return $response;
I get the object in "$request->input('entry');" in this part and I want to access the object like this $entryObj["mov_entry_ean13"];, when I send in Angular 7 with the Json as I show to you guys, my Laravel application access this is object fine, but my problem is on Android.
When I use Java in Android, I tried to make the object looks like the javascript way but with no success, I try JsonObject, JsonElement, and Map, this is my Retrofit API:
#FormUrlEncoded
#POST("/api/validateentrymobi")
public Call<JsonObject> validateTicket(
#Field("entry") JsonObject entry,
#Field("userid") String user_id
);
When I use I'm getting this error "Illegal string offset "mov_entry_ean13"", like is something wrong with my object that I'm sending, this is the object from java
{"mov_entry_id":72507,"plate":null,"mov_vehicle_id":1,"mov_vehicle_name":"Carro","value":"8.00","mov_area_id":7,"mov_area_name":"AB","mov_user_id":1,"validated":"N","mov_entry_ean13":"7800000725070","created_at":"02/07/2019 13:20:27","updated_at":"02/07/2019 13:20:27","validated_date":"2019-07-02 13:40:27"}
What I'm doing wrong?
You need to create a POJO and set up a json converter for Retrofit to use.
Setup Retrofit
Retrofit retrofit = new Retrofit.Builder()
.addConverterFactory(GsonConverterFactory.create()) // this requires implementation 'com.squareup.retrofit2:converter-gson:2.5.0'
.build()
Create a POJO class annotated with Gson
// this will act as the top level json object {}
class MyBody {
#SerializedName("mov_entry_id")
int movEntryId;
// write your fields here
}
Use the POJO as the body for Retrofit request
// you don't need the form unless your backend requires it
#POST("/api/validateentrymobi")
public Call<ResponseBody> validateTicket( // #NOTE the return type, you can create a POJO class similar to how I created MyBody and replace ResponseBody with it. But ResponseBody should work.
#Body MyBody myBody
);

How to correctly parse the JSON?

I have developed a Cordova android plugin for my library. The library is used for sending events across different connected devices.
JS interface receives a JSON from the java side. What I want to do is to parse this before reaching the application so that the developer can directly use it as a JS object. When I tried to parse the JSON in my plugin's JS interface, I am running into issues. Below is an example:
Received by JS interface:
{"key":"name","data":"{\"name\":\"neil\",\"age\":2,\"address\":\"2 Hill St\"}"}
After parsing in JS interface:
Object {key: "name", data: "{"name":"neil","age":2,"address":"2 Hill St"}"}
data:"{"name":"neil","age":2,"address":"2 Hill St"}"
key:"name"
__proto__:Object
As you can see, if this data reaches the app and the developer accesses the data:
eventData.key = name;
eventData.data = {"name":"neil","age":2,"address":"2 Hill St"};
eventData.data.name = undefined
How can I parse the inner data as well in my JS interface so that the developer can access directly. In the above case, he has to parse eventData.data to access the properties. I don't want this to happen and I want to do this in JS interface itself.
Please note that eventData can have many properties and hence they should be properly parsed before passing into the app.
I am new to Javascript and hence finding it difficult to understand the problem.
It seems that your returned JSON contains a string for the data property.
var response = {"key":"name","data":"{\"name\":\"neil\",\"age\":2,\"address\":\"2 Hill St\"}"};
//Parse the data
var jsonData = JSON.parse(response.data);
console.log(jsonData.name); //neil
console.log(jsonData.age); //2
console.log(jsonData.address);//"2 Hill St"
As others pointed out, you have to do JSON.parse(eventData.data) as the data comes as a string.
You have to look why that happens. The inner data might be stored in this way, in some cases its valid to store it in db as flat object or it is stringified twice by mistake:
var innerdata = JSON.stringify({ name: "neil" });
var eventData = JSON.stringify({ key: "name", data: innerdata });
would correspond to your received string.
Correct way to stringify in first place would be:
var innerdata = { name: "neil" };
var eventData = JSON.stringify({ key: "name", data: innerdata });

Json to Map Unsing Amcharts

I need to creat a Tunisia map using Amcharts with my json data
Code in my json / id in tunisiaLow
nbre in my json / value in tunisialow
i change in tunisiaLow like my json data but not work
i need samthink like this
pic
pleas help me
this is my code in plunker plnkr.co/edit/6aDJREhcFYSfM5JW99mX?p=preview
The biggest issue with your code is that you modified the AmCharts map JS file in such a way that it completely breaks with the library. The JS files should not be modified unless you know what you're doing and follow the directions on creating your own map files tutorial. Your modified file removes the required id attribute that makes the map function.
Ideally you should modify your data to match the map format, not the other way around. Going by your last ticket, you seem to be unable to change your data, so the solution is the same as the last - remap your data to conform with AmCharts' format.
The original JS/SVG map has a list of IDs for each province. Since your dataset's titles don't exactly match the titles within the original map, you'll want to create a lookup object that uses your titles to link up to the internal map IDs, for example, using your French titles:
var areaDataMapping = {
"TUNIS": "TN-11",
"ARIANA": "TN-12",
"BEN AROUS": "TN-13",
"MANOUBA": "TN-14",
"NABEUL": "TN-21",
"ZAGHOUAN": "TN-22",
"BIZERTE": "TN-23",
"BEJA": "TN-31",
"JENDOUBA": "TN-32",
"KEF": "TN-33",
"SILIANA": "TN-34",
"KAIROUAN": "TN-41",
"KASSERINE": "TN-42",
"SIDI BOUZID": "TN-43",
"SOUSSE": "TN-51",
"MONASTIR": "TN-52",
"MAHDIA": "TN-53",
"SFAX": "TN-61",
"GAFSA": "TN-71",
"TOZEUR": "TN-72",
"KEBILI": "TN-73",
"GABES": "TN-81",
"MEDENINE": "TN-82",
"TATAOUINE": "TN-83"
};
From there, you can remap your parsed JSON file to create the correct area object array with the required properties such as id, title and value and then assign the result to your code:
var remappedAreas = AmCharts.parseJSON( areas ).map(function(area) {
return {
id: areaDataMapping[area.libelleFr],
title: area.libelleAr,
code: area.code,
value: area.nbre
}
});
var map = AmCharts.makeChart("...", {
// ...
"dataProvider": {
// ...
"areas": remappedAreas,
// ...
},
// ...
});
Here's an updated plunkr, which uses the official AmCharts JS for Tunisia instead of your version.

How to structure and parse JSON

I'm creating a web RPG using HTML5 and JavaScript embedded directly into my website. The game will be a single player game against computer opponents... the design will be top-down 2D, Zelda style. It will be real time, but conversing with computer players will be scripted... they say something, and you're given some response options.
I was thinking of writing the dialog in XML, but I was told I should use JSON as it's easier to parse using JavaScript.
I saw Abstract Chaos' answer in XML...
<?xml version="1.0" encoding="UTF-8"?>
<npcs>
<npc name="Abstract">
<dialogue>
<text>Welcome #{PlayerName} to Stack Exchange, What would you like to know? </text>
<options>
<option action="dialogue5">Tell me about Stack Exchange?</option>
<option action="quest1">Give me quest</option>
<option action="object1">Give me object</option>
</options>
</dialogue>
<dialogue id="5">
<text>Stack Exchange is a fast-growing network of 87 question and answer sites on diverse topics</text>
<text>We build libraries of high-quality questions and answers, focused on the most important topics in each area of expertise</text>
</dialogue>
</npc>
</npcs>
And was wondering how I could achieve the same sort of layout in JSON...
My questions are:
How can I layout RPG dialog scripts in JSON to be parsed by JavaScript?
Can I have an example of how I could use JavaScript logic to parse JSON given certain conditions (ex: NPC asks question: "Can you help me?", JSON should have options "Yes" and "No", which could be based on if the player actually has that skill set to help).
The JSON dialog text will be stored in a separate "dialog" folder in my project folder... so it will need to be accessed externally
The only thing I've found on how to layout and parse JSON is:
var json = '{"result":true,"count":1}',
obj = JSON && JSON.parse(json) || $.parseJSON(json);
alert(obj.result);
But it doesn't have the neatness factor that XML seems to have.
Any help would be appreciated...
Thanks!
Trying to load and alert external JSON text file doesn't work:
HTML:
<html>
<head>
<title>Working with JSON</title>
<script src="jquery.js"></script>
<script>
(function() {
var data = "/JSON_TEXT.txt";
var first_q = data.npcs[0].dialogs[0];
alert(first_q.text);
}());
</script>
</head>
<body>
</body>
</html>
JSON plain text file: JSON_TEXT.txt
'npcs': [
{
'name': 'Abstract',
'dialogs': [
{
'text': 'Welcome',
'options': [
'df', 'f'
]
}
]
}
]
How can I layout RPG dialog scripts in JSON ?
The equivalent of the XML you gave us would be (without the comments):
// you might use a top wrapper object with a property "npcs" for this array
[
{
"name": "Abstract",
"dialogues": {
// I recommend on object with dialogues by id instead of an array
"start": {
"texts": [
"Welcome #{PlayerName} to Stack Exchange, What would you like to know?"
],
"options": [
{
"action": "dialogue 5",
"text": "Tell me about Stack Exchange?"
}, {
"action": "quest 1",
"text": "Give me quest"
}, {
"action": "object 1",
"text": "Give me object"
}
]
},
"5": {
"texts": [
"Stack Exchange is a fast-growing network of 87 question and answer sites on diverse topics",
"We build libraries of high-quality questions and answers, focused on the most important topics in each area of expertise"
]
}
}
// further properties of the NPC like objects and quests maybe
},
… // further NPCs
]
How to parse JSON?
See Parse JSON in JavaScript?.
var json = {…};
var data = JSON && JSON.parse(json) || $.parseJSON(json);
Ouch, no! That's no JSON, that's just an object literal in JavaScript. You can use it like
var data = {…};
and data will be your object. You need to parse JSON only when you have it as a string, for example when you've loaded a file via ajax.
JavaScript logic to parse JSON given certain conditions
That's your game logic, with which we can't help you. But you don't need to parse JSON there, you only need to access the data which you have already parsed. See Access / process (nested) objects, arrays or JSON for that.
Some find JSON harder to read than XML. I think it's much cleaner and easier to use, especially if you want to parse it with JS.
That said, I'm not really sure what your question is—you already have the data in XML, so just convert it to JSON. You can use arrays ([]) for lists and objects ({}) for when you need named keys:
{
'npcs': [
{
'name': 'Abstract',
'dialogs': [
{
'text': 'Welcome #{PlayerName} to Stack Exchange, What would you like to know?',
'options': [
//options here
]
},
//next dialog object here
]
},
//next npc object here
]
}
So, like you said, first you'll need to parse the JSON string:
var json; //contains the json string, perhaps retrieved from a URL via AJAX
data = JSON && JSON.parse(json) || $.parseJSON(json);
You could also assign the JSON object to a JS variable in the first place (say, in a .js file somewhere) and you won't need to parse at all. Just be sure not to pollute the global scope.
After parsing, data is a normal JS object. You can access its properties just like any other object. So, to access the first question from the first NPC, do:
var first_question = data.npcs[0].dialogs[0];
Let's alert the question itself:
alert(first_question.text);
You can access its options like this:
first_question.options;
You asked about how to load the JSON data from an external file. The usual approach is to load the file's URL via AJAX. Here is a nice tutorial for making AJAX requests with vanilla JavaScript: https://developer.mozilla.org/en-US/docs/AJAX/Getting_Started
But there's not much reason to hand-code AJAX requests with vanilla JavaScript. I recommend using a library like jQuery, which has handy AJAX functions such as .ajax and the shorthand function .get. Here's an example using .get:
var data; //will hold the parsed JSON object
var json_url = 'json.txt'; //URL of your JSON (just a plain text file)
$.get(json_url, function(json) {
data = JSON && JSON.parse(json) || $.parseJSON(json);
});
//use data here

Serialize MVC model to JSON

I am trying to do a very simple task: get an MVC model, and send it back to server as JSON. I tried
#Html.Raw(Json.Encode(Model));
When debugging the JS, I see that the date objects on the serialized JSON look like: /date (00064321)/ and when passing the serialized JSON to the server, the dates are null on the server-side. Anyone understand what is going on?
Instead of JSON encoding the model directly you have to create an anonymous object converting the date-time properties to strings.
Ex.
var meeting = new Meeting
{
Name = "Project Updates",
StartDateTime = DateTime.Now
};
Passing directly the model..
#Html.Raw(Json.Encode(meeting))
produces
{"Name":"Project Updates","StartDateTime":"\/Date(1338381576306)\/"}
and
#Html.Raw(Json.Encode(new {
Name = meeting.Name,
StartDateTime = meeting.StartDateTime.ToString()
}))
produces
{"Name":"Project Updates","StartDateTime":"5/30/2012 6:09:36 PM"}
as expected.

Categories

Resources