I have following json created after I sereliaze a dictionary
{"Results":["{\"BaseCurrency\":\"USD\",\"TermCurrency\":\"JPY\"}","{\"BaseCurrency\":\"USD\",\"TermCurrency\":\"JPY\"}","{\"BaseCurrency\":\"USD\",\"TermCurrency\":\"JPY\"}","{\"BaseCurrency\":\"USD\",\"TermCurrency\":\"JPY\"}"],"Total":4}
When I try to load it into the extjs store , the store is not loaded
var store = Ext.create('Ext.data.Store', {
fields: fields,
pageSize: itemsPerPage,
proxy: {
type: 'ajax',
url: getDataWithPageURL,
reader: {
type: 'json',
root: 'Results',
totalProperty: 'Total'
}
}
});
But if I remove slash hard coded and it's working
{"Results":["{"BaseCurrency":"USD","TermCurrency":"JPY"}","{"BaseCurrency":"USD","TermCurrency":"JPY"}","{"BaseCurrency":"USD","TermCurrency":"JPY"}","{"BaseCurrency":"USD"}"],"Total":4}
I create json using Newtonsoft.Json
Dictionary<string, object> dict = new Dictionary<string, object>();
string s = JsonConvert.SerializeObject(dist);
How can I remove slash in server side in order to produce valid json for extjs store.
I tried
result = result.Replace("\"","'");
And
result =result.Replace("\"", #"""")
It's not working
Clearly, Ext doesn't like that you have encoded a json object as a string and then put them in another json object. You have two options that I see.
See if you can return the dict on the server-side without first converting it into a string. Some code, somewhere, is taking your string and putting it in a json object with 'Results' and 'Total'. Check to see if that code can take a Dictionary as-is.
Unwrap the 'Results' propery on the client-side. One way would be to make your own reader:
Ext.define('MyReader', {
extend: 'Ext.data.reader.Json',
alias: 'reader.my-json',
read: function(object) {
object.Results = Ext.Array.map(object.Results, Ext.decode);
return this.callParent([object]);
}
});
Then use type: 'my-json' in your reader config.
Here is my test case:
var data = {"Results":["{\"BaseCurrency\":\"USD\",\"TermCurrency\":\"JPY\"}","{\"BaseCurrency\":\"USD\",\"TermCurrency\":\"JPY\"}","{\"BaseCurrency\":\"USD\",\"TermCurrency\":\"JPY\"}","{\"BaseCurrency\":\"USD\",\"TermCurrency\":\"JPY\"}"],"Total":4};
Ext.define('Currency', {
extend: 'Ext.data.Model',
fields: [
{ name: 'BaseCurrency', type: 'string' },
{ name: 'TermCurrency', type: 'string' }
]
});
Ext.define('MyReader', {
extend: 'Ext.data.reader.Json',
alias: 'reader.my-json',
read: function(object) {
object.Results = Ext.Array.map(object.Results, Ext.decode);
return this.callParent([object]);
}
});
var store = Ext.create('Ext.data.Store', {
model: 'Currency',
data: data,
proxy: {
type: 'memory',
reader: {
type: 'my-json',
root: 'Results',
totalProperty: 'Total'
}
}
});
Related
I am passing array of json objects from ajax method.
var FieldValue = {
Key: $(this).attr("id"),
Value: $(this).val()
};
FieldValues.push(FieldValue);
$.ajax({
url: "../Handler.ashx?&Action=Save",
data: JSON.stringify(FieldValues),
type: "post",
datatype: "json",
contentType: "application/json; charset=utf-8",
});
But when i tried to deserialize to List of dictionary.
JavaScriptSerializer javaScriptSerializer = new JavaScriptSerializer();
List<Dictionary<string, string>> WebFields = new List<Dictionary<string, string>>();
WebFields = javaScriptSerializer.Deserialize<List<Dictionary<string, string>>>(jsonString);
My expected output list is like,
string Key = WebFields[0].Key
string Value = WebFields[0].Value
But now it is like each WebField item is like,
WebFields[0] -> [0] -> Key
[1] -> Value
How to achieve my expected output ?
To get a dictionary server side, try to send a basic POJO.
Instead of:
var FieldValue = {
Key: $(this).attr("id"),
Value: $(this).val()
};
FieldValues.push(FieldValue);
try:
var key = $(this).attr("id");
var value =$(this).val()
var fieldValue = { key: value };
fieldValues.push(fieldValue);
A javascript object is represented as a key value pair, thus returning a Dictionary will return a JS object with the key being propname, and value being the value
I wish to simply do an AJAX call to a method expecting a List of Key and value pairs, but I have no idea how to do this. I tried the following:
Server method:
UpdateBranches(List<KeyValuePair<string, string>> brancheItems)
data to be send:
var brancheItems = [];
businessActivities.forEach(f =>
brancheItems.push({
Key: f.sbiCode,
Value: f.sbiCodeDescription
})
This seemed to give me an array of objects with key and value properties. (network tab showed it), but it did not work. I also tried to make an array of objects with one property (propertyname is the key, value is the value):
for (var itemIndex in items[index].businessActivities) {
var key = items[index].businessActivities[itemIndex].sbiCode;
brancheItems.push({
key: items[index].businessActivities[itemIndex].sbiCodeDescription
});
}
Note that on the server I seem to receive an array/list of 3 items with two properties, but the properties are always empty. Does anyone know the correct format for the data to be send
I think you can simply create your object like this:
var ParamtersContainer = new Object();
ParamtersContainer = {
"PatientName": 'Alameer',
"ServiceDate": '12/12/2017',
"ProviderName": 'ahmed'
};
Then make it as data parameter in your ajax request, receive it as a dictionary in your c# action.
Use something like this.
$.ajax({
type: 'POST',
url: url,
contentType: "application/json",
data:JSON.stringify( {brancheItems: brancheItems}),
success: function (data) {
alert("Succeded");
}
});
And use the bracket notation:
Instead of brancheItems.push({ key : value });
use
var object = {};
object[key] = value;
brancheItems.push(object);
I get this type of JSON data from Web API:
Data: {
FromDate: "2016-03-01",
Comment: "Bla bla",
...
},
FieldInfo: {
Items: [
{
Id: "FromDate",
Required: true,
DataType: "date"
},
{
Id: "Comment",
Required: true,
DataType: "string"
},
...
]
}
I need to serialize it to C# object and transform it to different representaion which should look something like this:
{
FieldInfo: {
Items: [
{
Id: "FromDate",
Required: true,
DataType: "date",
Value: "2016-03-01"
},
{
Id: "Comment",
Required: true,
DataType: "string"
Value: "Bla bla"
},
...
]
}
Basically map field values to its schema so it will not be separated.
Of course easiest way its just write a lot of if's for each field, which will not be very elegant solution and even not doable if we take into account that field schema and fields are dynamic so they can change. Property which I can rely on is Id in FieldInfo Item schema which should be a property name in Data object. One of the solution might be to use reflection in order to map Id value to property name in C# object representation. My question maybe there is another solution(s) to this problem or some tools which can help me in achieving this goal?
Using JSON.NET, you can parse the JSON into a JObject and manipulate it like so:
// Parse your json string into a JObject
JObject o = JObject.Parse(json);
// Retrieve the "Data" part of the json, i.e,
// the object that contains the values
var data = o["Data"];
// Retrieve the "FieldInfo" part. We will add values to this part.
var fieldInfo = o["FieldInfo"];
foreach (var token in fieldInfo["Items"])
{
var item = (JObject) token;
// Add the Value property to each item, get the value from the
// corresponding field
item["Value"] = data[(string)item["Id"]];
}
The variable fieldInfo will contain the information you wanted. Of course, it would be cleaner to create a new JObject to contain the information. But the example shows how you can retrieve and map the values you require.
You will have to implement some form of custom json converter to get the required output you desire to your new class structure. JSON.NET Custom JsonConverter:
http://www.newtonsoft.com/json/help/html/CustomJsonConverter.htm
Here is a nice beginners tutorial on how this is achieved:
http://geekswithblogs.net/DavidHoerster/archive/2011/07/26/json.net-custom-convertersndasha-quick-tour.aspx
I am POSTing a JSON object to a controller action:
$.ajax({
url: "/path/to/action",
type: "POST",
dataType: "json",
data: {
name: "John Doe",
phone: "2323454543",
skills: {
code: "php",
design: "photoshop"
}
}
});
How can I map this data to some kind of key-value pair object? In PHP, these get mapped to an associative array invisibly. I would like to be able to access properties like this:
SomeDynamicType data = ...//something here to prepare json data
string codeSkills = data.skills.code; //codeSkills should = "php"
I'm not interested in model binding since these value do not correspond to a model - they are arbitrary.
In your .ajax call stringify Json:
data: {
json:
JSON.stringify({
name: "John Doe",
phone: "2323454543",
skills: {
code: "php",
design: "photoshop"
}
})
}
And accessing properties how you wanted in your controller:
[HttpPost]
public JsonResult Action(string json)
{
dynamic data = Newtonsoft.Json.JsonConvert.DeserializeObject<dynamic>(json);
string codeSkills = data.skills.code;
...
codeSkills is "php" string.
Newtonsoft Json library is available since .NET 4, if I recall correct.
Try using JSON.NET, this library parses JSON into a dictionary-like structure. It is used as follows:
JObject rss = JObject.Parse(json);
string codeSkills = (string)rss["skills"]["code"];
i'd like to better understand the issue of casting object to a name vs value collection
say ...just if i could do it like that
1) does the java-script needs some fine tuning ? packing the data..
2) and most important for me : What is the correct way to do the conversion from that key value Js to a Dictionary<T,T> C# ?
the Aspx / Html part
<input type="text" id="tbx_Name" value="Avi" />
<input type="text" id="tbx_City" value="TelAviv" />
<input type="text" id="tbx_Country" value="Israel" />
<select id="ChosenRandomClass" style="display:none">
<option selected="selected" value="0">(choose a random)</option>
<option value="1">random Top Beach</option>
<option value="2">random Top Center</option>
<option value="3">random Local Pub</option>
</select>
the JavaScript / jQuery part
function AddNew() {
if (!confirm("would you like to add this contact ?")) return;
var Name = $('#tbx_Name').val();
var City = $('#tbx_City').val();
var Country = $('#tbx_Country').val();
var selectedRC = $('#ChosenRandomClass option:selected').val();
var hDate = []
var param1 = { key: "Name", value: Name };
var param2 = { key: "City", value: City };
var param3 = { key: "Country", value: Country };
var param4 = { key: "SelctedClass", value: selectedRC };
hDate.push(param1);
hDate.push(param2);
hDate.push(param3);
hDate.push(param4);
// is this part necessary the data will not get to
// code behind properly without the serializing ?
var startPrt = Sys.Serialization.JavaScriptSerializer.serialize(hDate);
ajaxUpdate("addNew", startPrt);
}
the Code behind C# part
public void AddNewRecord(object startPrt)
{
Dictionary<string, string> SenthDate = new Dictionary<string, string>();
// .....etc
}
i will appreciate the correct answer
thanks for your kind help and time.
I gave your sample a try and noticed that the startPrt parameter is actually being received as an Array of Dictionary(string, object). Hence, if you make the AJAX call like this:
var hDate = [];
hDate.push({ key: "Name", value: Name });
hDate.push({ key: "City", value: City });
hDate.push({ key: "Country", value: Country });
hDate.push({ key: "SelctedClass", value: selectedRC });
$.ajax({
contentType: 'application/json; charset=utf-8',
url: 'MyPage.aspx/AddNewRecord',
type: 'POST',
data: JSON.stringify({ startPrt: hDate }),
success: success, // success callback
error: error // error callback
});
You can define your WebMethod like the follwoing to convert the startPrt parameter to a dictionary:
[WebMethod]
public static void AddNewRecord(object startPrt)
{
var dict = new Dictionary<string, object>();
foreach (Dictionary<string, object> pair in (Array)startPrt)
dict.Add((string)pair["key"], pair["value"]);
}
The conventional approach would be to construct a plain javascript object, which can be used by jQuery.ajax(...) without any pre-processing.
var hDate = {
"Name": $('#tbx_Name').val(),
"City": $('#tbx_City').val(),
"Country": $('#tbx_Country').val(),
"SelctedClass": $('#ChosenRandomClass').val()
};
ajaxUpdate("addNew", hDate);
In ajaxUpdate(), the ajax expression will be something like this :
function ajaxUpdate(action, data) {
...
$.ajax({
url: '...',
data: data,
...
success: function(){
...
}
});
}
Thus the serialized data will made available to the server-side script of whatever flavour.