JSON.parse for array of object - javascript

Server returns the array of object in JSON. It looks so:
{"d":"[
{\"Id\":1,\"IsGood\":true,\"name1\":\"name1dsres\",\"Name2\":\"name2fdsfd\",\"name3\": \"name3fdsgfd\",\"wasBorn\":\"\\/Date(284011000000)\\/\"},
{\"Id\":2,\"IsGood\":false,\"name1\":\"fdsfds\",\"name2\":\"gfd3im543\",\"name3\":\"3543gfdgfd\",\"WasBorned\":\"\\/Date(281486800000)\\/\"}
]"}
I need to parse using JSON.parse function. I'm doing this this way:
function myFunction(dataFromServer){
var parsedJSON = JSON.parse(dataFromServer.d);
for (var item in parsedJSON.d) {
// how do I get the fields of current item?
}
This code is not working, it returns undefined
for (var item in parsedJSON) {
alert(item.Id);
}

This works perfectly
function myFunction(dataFromServer){
var parsedJSON = JSON.parse(dataFromServer.d);
for (var i=0;i<parsedJSON.length;i++) {
alert(parsedJSON[i].Id);
}
}
But this doens't
function myFunction(dataFromServer){
var parsedJSON = JSON.parse(dataFromServer.d);
for (var item in parsedJSON) {
alert(item.Id);
}
}

You can just access them as you would any object:
var id = item.Id;
if (item.IsGood) { ... }
If you wish to enumerate them to use somehow, have a look at this SO question.

You can access them as you do oridinary javascript objects,
that is either as item.id or item['id']

class Program
{
static void Main(string[] args)
{
var jsonString = #"{
""data"": [
{
""uid"": ""100001648098091"",
""first_name"": ""Payal"",
""last_name"": ""Sinha"",
""sex"": ""female"",
""pic_big_with_logo"": ""https://m.ak.fbcdn.net/external.ak/safe_image.php?d=AQAi8VLrTMB-UUEs&bust=1&url=https%3A%2F%2Fscontent-a.xx.fbcdn.net%2Fhprofile-ash2%2Fv%2Ft1.0-1%2Fs200x200%2F10018_433988026666130_85247169_n.jpg%3Foh%3Dc2774db94dff4dc9f393070c9715ef65%26oe%3D552CF366&logo&v=5&w=200&h=150"",
""username"": ""payal.sinha.505"",
},
]
}";
dynamic userinfo = JValue.Parse(jsonString);
IList<FacebookUserDetail> userDeatils = new List<FacebookUserDetail>();
// 1st method
foreach (dynamic userinfoItr in userinfo.data)
{
FacebookUserDetail userdetail= userinfoItr.ToObject<FacebookUserDetail>();
userDeatils.Add(userdetail);
}
// 2nd Method
var userDeatils1 = JsonConvert.DeserializeObject<FacebookUserDetails>(jsonString);
}
}
public class FacebookUserDetail
{
public string username { get; set; }
//Password = EncryptionClass.Md5Hash(Guid.NewGuid().ToString()),
public string first_name { get; set; }
public string last_name { get; set; }
public string sex { get; set; }
public string pic_big_with_log { get; set; }
}
enter code here
public class FacebookUserDetails
{
public IList<FacebookUserDetail> data { get; set; }
}
}

Related

Load partial view by sending javascript data array as parameter

This is my javascript to load partial view by sending a data array as a parameter.
$('body').on('click', '.btn-add-answer', function () {
var answerObj = Array.from(GetAnswerDetails(this));
var lastAnswer = answerObj[answerObj.length - 1];
var answers = {};
answers.Id = parseInt(lastAnswer.Id) + 1;
answers.FormQuestionId = lastAnswer.FormQuestionId;
answers.Text = "";
answers.IsCorrect = false;
answers.Score = null;
answers.QuestionAnswerId = 0;
answers.Sequence = 0;
answerObj.push(answers);
$("#survey-answer-container")
.load("LoadTest", answerObj);
});
This is my controller
public ActionResult LoadTest(List<AnswerDto> answers)
{
return PartialView("_SurveyPageSectionQuestionAnswer", answers);
}
And this is my DTO
public class AnswerDto
{
public int Id { get; set; }
public string Text { get; set; }
public int Sequence { get; set; }
public bool? IsCorrect { get; set; }
public int? Score { get; set; }
public int FormQuestionId { get; set; }
public int QuestionAnswerId { get; set; }
}
The issue is the parameter didn't get to the controller. The 'answers' parameter in the controller will only have default values.
How to send data array from javascript as a parameter in partial view load?
Try your object like below. Wrap your object as { answers: answerObj } so it could match with parameter name.
$("#survey-answer-container")
.load("LoadTest", { answers: answerObj });

C# SHA512 to Hex string

There's a javascript library called Crypto-js and i'm trying to convert some methods I use to c#.
For example in javascript:
var payload = JSON.stringify({ market: "BTC-ETH", order: { price: "0.02159338", side: "buy", size: "0.024" } });
var contentHash = cryptoJS.SHA512(payload).toString(cryptoJS.enc.Hex);
console.log(contentHash);
In C#
public class OrdersVM
{
public string Market { get; set; }
public Order Order { get; set; }
}
public class Order
{
public string Price { get; set; }
public string Side { get; set; }
public string Size { get; set; }
}
public async Task<IActionResult> Orders([FromBody] OrdersVM vm) {
var payload = JsonConvert.SerializeObject(vm);
var contentHash = sha512Hex(payload).ToLower();
Console.WriteLine(contentHash);
}
public string sha512Hex(string input)
{
var bytes = Encoding.UTF8.GetBytes(input);
using (var hash = SHA512.Create())
{
hash.ComputeHash(bytes);
return BitConverter.ToString(hash.Hash).Replace("-", "");
}
}
contentHash for javascript is
"99bb05af8aace509189e08625bb4e475a9daaafc92edf5c85fa1aefcc16c16e4533c23843c5806aef01c97e8cb4150b2dc129d04d3b6a50331833fe5cb8158fc"
and for c#
"731b92cf482ff90ffe759e356959ec005334062bdc3c2cc78b48c3041d21a45ecaa6b33f6df2971fa868f94f04b7596e818104cb1017ed1c436365beac3a01d1"
What am I doing wrong with c# conversion?
The issue is that JSON.Net, by default, will serialise your property names exactly as the appear, meaning they all start with a capital letter. There are two ways to fix this:
Using JsonProperty to explicitly control the property name serialisation. For example:
public class OrdersVM
{
[JsonProperty("market")]
public string Market { get; set; }
[JsonProperty("order")]
public Order Order { get; set; }
}
Use a contract resolver to tell JSON.Net how to process the names. Fortunately there is one provided for you that will do this:
var settings = new JsonSerializerSettings
{
ContractResolver = new CamelCasePropertyNamesContractResolver()
}
var payload = JsonConvert.SerializeObject(vm, settings);

How can I convert javascript var obj = {}; to C#?

I have the following javascript code:
var key = "Mykey" + NextNumber.toString();
var value = {"Name":"Tony","Width":"150","Height":"320"};
var valuejson = JSON.stringify(value);
var obj = {};
obj[key] = valuejson
I know how to create valuejson in C#, but I don't know how to create something similar like var obj = {}; in C#. How can I do that in C#?
key and valuejson in C#:
public class MyValue
{
public string Name { get; set; }
public string Width { get; set; }
public string Height { get; set; }
}
MyValue value = new MyValue();
value.Name = "Tony";
value.Width = "150";
value.Height = "320";
string jsonValue = JsonConvert.SerializeObject(value);
string key = "Mykey" + NextNumber.toString();
You could try to use a dynamic object which works similar to {} in javascript... But... You have to be CAREFUL, example:
public class test
{
public class MyValue
{
public string Name { get; set; }
public string Width { get; set; }
public string Height { get; set; }
}
public void testing()
{
MyValue value = new MyValue();
value.Name = "Tony";
value.Width = "150";
value.Height = "320";
dynamic jsonValue = new { keyA = value };
string height = jsonValue.keyA.Height;
}
}
EDI:
Actually, I read a bit more carefully your need, and a dictionary can also suit your needs:
public class test
{
public class MyValue
{
public string Name { get; set; }
public string Width { get; set; }
public string Height { get; set; }
}
Dictionary<string, MyValue> dic = new Dictionary<string, MyValue>();
public void testing()
{
string key = "Mykey" + NextNumber.toString();
MyValue value = new MyValue();
value.Name = "Tony";
value.Width = "150";
value.Height = "320";
dic.Add(key, value);
}
}
Since you where asking for the equivalent of a var x = {} I suggested the dynamic but I see you want to create a key and associate that value to that key.
If you're looking for an object whose members can be dynamically added and removed at run time (like in Javascript) then the ExpandoObject class should fit your needs.
dynamic employee = new ExpandoObject();
employee.Name = "John Smith";
employee.Age = 33;
foreach (var property in (IDictionary<String, Object>)employee)
{
Console.WriteLine(property.Key + ": " + property.Value);
}
// This code example produces the following output:
// Name: John Smith
// Age: 33
You are asking for dynamic ExpandoObject.
Example:
dynamic obj = new ExpandoObject();
obj.banana = "CIAO";
obj.bidshmqwq = 11245;
obj.BRUFCJMWH = null;
In substance, this Type can let you declare object's properties dynamically.
To convert from a json string to a C# object, you can use the DeserializeObject method and pass in an instance of the c# object that you want to convert this json to. The JsonConvert library is part of the Newtonsoft.Json library.
var converted = JsonConvert.DeserializeObject<myCSharpViewModel>(json);

Error posting record to db asp.net mvc

I am building a scheduling system using fullcalendar for MVC, my get event retrieves from a view for a specific location.
However, my post / save event inserts into the table that the view is made from, containing all locations.
I am getting an error when I try to add the new event to the data connection.
"The field Location must be a string or array type with a maximum length of '1'." string
PropertyName "Location" string
I tried to set the string for the event manually before adding it to the data connection but this isn't working for some reason. Could it be me not declaring the string correctly?
//Actions for Calendar 5
public JsonResult GetEvents5()
{
using (CalgaryNEEntities dc = new CalgaryNEEntities())
{
var events = dc.CalgaryNEEvents.ToList();
return new JsonResult { Data = events, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
}
}
[HttpPost]
public JsonResult SaveEvent5(EventsAllLocation e)
{
var status = false;
using (InsertEntities dc = new InsertEntities())
{
if (e.EventID > 0)
{
//Update the event
var v = dc.EventsAllLocations.Where(a => a.EventID == e.EventID).FirstOrDefault();
if (v != null)
{
var locationstring = "Calgary NE Kitchens";
v.CompanyName = e.CompanyName;
v.Start = e.Start;
v.End = e.End;
v.KitchenNumber = e.KitchenNumber;
v.Location = locationstring;
}
}
else
{
var locationstring = "Calgary NE Kitchens";
e.Location = locationstring;
dc.EventsAllLocations.Add(e);
}
dc.SaveChanges();
status = true;
}
return new JsonResult { Data = new { status = status } };
}
Here is the EventsAllLocation definition:
public partial class EventsAllLocation
{
public int EventID { get; set; }
public string Location { get; set; }
public string CompanyName { get; set; }
public System.DateTime Start { get; set; }
public Nullable<System.DateTime> End { get; set; }
public string KitchenNumber { get; set; }
}
Any tips or help would be greatly appreciated, thanks!
The answer is staring you in the face !! LOL
"The field Location must be a string or array type with a maximum
length of '1'." string PropertyName "Location" string

Controller do not receive values passed from json.stringify(obj)

I am not understand this case:
I have a model like:
public class ExmDescobertos {
public int Id { get; set; }
public int ExameId { get; set; }
public int PlanoId { get; set; }
public int ConvenioId { get; set; }
}
And create an object javascript:
var objDescoberto = new Object();
objDescoberto.Id = $("#hdnDescobertoId").val(); //inputs with values...
objDescoberto.ExameId = $('#hdnExameId').val();
objDescoberto.PlanoId = $('#hdnPlanoId').val();
objDescoberto.ConvenioId = $('#hdnConvenioId').val();
And I am using Json.stringify(obj) to transmit the values with a $.post jQuery method:
var dados = JSON.stringify(objDescoberto);
In this point, dados is "{"Id":"27","ExameId":"53","PlanoId":"32","ConvenioId":"11"}", for example.
And have a controller with this action:
public PartialViewResult(ExmDescobertos descoberto) { }
But... the parameter in this controller not receive your values correct! :o
In this point descoberto is Id = 0; ExameId = 0; PlanoId = 0; ConvenioId = 0;
Not errors explicit, but not works...
Anybody have a idea of what I have missing?
Thank you for all!
Don't stringify you object, just send object as is.
$.post("/url", objDescoberto);
or
var dados = JSON.stringify({descoberto : objDescoberto});

Categories

Resources