How to parse json array into controller in MVC? - asp.net-mvc-4

I am working on ASP.NET MVC 4.0 application.
I am sending my form's value to controller like this in Kendo Window refresh option :-
var frm = $("#formUpdate");
var productWindow = $("#ProductWindow").data("kendoWindow");
productWindow .refresh({
url: "../../Product/UpdateProduct",
data: { model: JSON.stringify(frm.serializeArray())}
});
And below is the string that i am getting on controller :-
[{"name":"DefaultAddressNumber","value":""},{"name":"Id2","value":"tax id 1"}, {"name":"Id2","value":"tax id 2"},{"name":"Id","value":"5"},{"name":"ProductTaxes","value":""},{"name":"ProdcutId","value":"20"},{"name":"InsuranceId","value":""},{"name":"OrgAddr1","value":""},{"name":"OrgAddr2","value":""},{"name":"OrgAddr3","value":""},{"name":"Name","value":"Amit Kumar"},{"name":"Description","value":"Description"},{"name":"SelectedProductSubTypeId","value":""},{"name":"IsEmailFinalizedProduct","value":"False"}]
And i want to do deserialize that string again into form of array or object or something in which i can read/get it easily.
And for that i have used below code :-
var productString = Newtonsoft.Json.JsonConvert.DeserializeObject<ProductViewModel>(str);
But i am getting the below error while i am using this :
Cannot deserialize the current JSON array (e.g. [1,2,3]) into type
'ProductRepository.ViewModel.ProductViewModel' because the type
requires a JSON object (e.g. {"name":"value"}) to deserialize
correctly.
To fix this error either change the JSON to a JSON object (e.g.
{"name":"value"}) or change the deserialized type to an array or a
type that implements a collection interface (e.g. ICollection, IList)
like List that can be deserialized from a JSON array.
JsonArrayAttribute can also be added to the type to force it to
deserialize from a JSON array.
Path '', line 1, position 1.
Can any one help me out on this,means how can i parse this string ?

use JSON.stringify to outer side like..
var frm = $("#formUpdate");
var productWindow = $("#ProductWindow").data("kendoWindow");
productWindow .refresh({
url: "../../Product/UpdateProduct",
data: JSON.stringify({ model: frm.serializeArray()})
});

Related

Mongoose: Why to convert a received data toObject

I was learning mongoose, and I am trying to figure out.
Why toObject() was needed to convert the data received into Object, when it was already in object form it seems
Here is the code:
UserSchema.methods.toJSON = function() {
var user = this;
var userObject = user.toObject();
return _.pick(userObject, ['_id', 'email']);
};
I cannot understand why toObject() was used to extract the meaningful properties from the object.
Thanks
toObject is a mongoose document method Document.prototype.toObject() which:
Converts this document into a plain javascript object, ready for storage in MongoDB.
You can more about it here
The reason it is called there is because a plain JS object is required in order to do the lodash _.pick which would create a new object with only _id and email properties.

RESTful API call in SSIS package

As part of a SSIS (2005) package I am calling a RESTful API through a script component (VB.NET). I am getting the records back OK. The problem I have though is processing the format it comes back in so I can output it (split into the separate output columns) within the data flow and write into a SQL table. Don't know where to start - anyone got any ideas? I have no control over the API so am stuck with this format.
Here is the schema as per the API documentation:
{StatusMessage : <string>, Unit : <string> [ { VehicleID : <int>, RegistrationNumber : <string>, DistanceTravelled : <double>} ] }
And here is a sample of the data returned (it comes back as a single line of text):
{"VehicleDistance":
[
{
"VehicleId":508767,
"RegistrationNumber":"BJ63 NYO",
"DistanceTravelled":0.09322560578584671
},
{
"VehicleId":508788,
"RegistrationNumber":"BJ63 NYL",
"DistanceTravelled":6.1591048240661621
},
{
"VehicleId":508977,
"RegistrationNumber":"PE12 LLC",
"DistanceTravelled":60.975761413574219
},
{
"VehicleId":510092,
"RegistrationNumber":"BJ64 FCY",
"DistanceTravelled":14.369173049926758
},
{
"VehicleId":510456,
"RegistrationNumber":"BJ63 NYY",
"DistanceTravelled":4.04599142074585
},
{
"VehicleId":513574,
"RegistrationNumber":"BL64 AEM",
"DistanceTravelled":302.150390625
}
],
"StatusMessage":null,
"Unit":"imperial",
"HttpStatus":200
}
This is Javscript Object Notation AKA JSON and you need to deserialise it. The problem is that using SSIS is tricky with third party tools that are popular (and fast) but VB.Net actually has a built in class to serialise and deserialise JSON called JavaScriptSerializer
First add a Reference to your project called System.Web.Extensions and then you can use the JavaScriptSerializer to deserialise your JSON.
I've put your JSON in a file for easier handling so first I have to...
Dim sJSON As String = ""
Using swReadFile As New System.IO.StreamReader("E:\JSON.txt")
sJSON = swReadFile.ReadToEnd()
End Using
The rest is the pertinent bit, so first add 2 Imports...
Imports System.Collections.Generic
Imports System.Web.Script.Serialization
Then for example we can...
Dim lvSerializer As JavaScriptSerializer = New JavaScriptSerializer()
lvSerializer.MaxJsonLength = 2147483644
Dim dictParsedJSONPairs As Dictionary(Of String, Object) = lvSerializer.Deserialize(Of Dictionary(Of String, Object))(sJSON)
If dictParsedJSONPairs.ContainsKey("VehicleDistance") AndAlso _
TypeOf dictParsedJSONPairs("VehicleDistance") Is ArrayList Then
Dim ArrayEntries As ArrayList = DirectCast(dictParsedJSONPairs("VehicleDistance"), ArrayList)
For Each ArrayEntry As Object In ArrayEntries
Dim DictEntry As Dictionary(Of String, Object) = DirectCast(ArrayEntry, Dictionary(Of String, Object))
If DictEntry.ContainsKey("VehicleId") Then Console.WriteLine("VehichleId:" & DictEntry("VehicleId"))
Next
End If
If dictParsedJSONPairs.ContainsKey("Unit") Then
Console.WriteLine("Unit is " & dictParsedJSONPairs.Item("Unit"))
End If
Clearly you should research JSON before launching into serious use. The object can be nested JSON (i.e. Dictionary(Of String, Object)), a number of some sort, a string or an ArrayList
It could be a bit late but you may want to have a look at json.net from Newtonsoft (website). The component provided contains .Net 2.0 version.
Using it in a SSIS script task is quite simple. I did it in SSIS2008 based on .Net 3.5 to parse JSON string like below. And according to the document, it should work for .Net 2.0 version as well.
//I assume you had obtained JSON in string format
string JasonBuffer;
//define Json object
JObject jObject = JObject.Parse(JasonBuffer);
//In my example the Json object starts with result
JArray Results = (JArray)jObject["result"];
//loop the result
foreach (JObject Result in Results)
{
//for simple object
JObject joCustomer = (JObject)Result["Customer"];
//do something...
//for complex object continue drill down
foreach (JObject joSection in Result["Sections"])
{
foreach (JObject joDepartment in joSection["Departments"])
{
foreach (JObject joItem in joDepartment["Items"])
{
}
You can find some actual code here: link

Jtable field options not display json because it contains /(slashes)

My wcf project returns the Countries List as json, in wcf project parse using Newtonsoft json. I get json in my client website built on mvc, i show the data using jtable plugin in jquery. The plugin failed to display because, the json contains /(back slashes).
Code to display jtable is
Name:{
title: 'Country Name',
width: '40%',
options: '/Country/Index'
}
Country/Index result is
{"Result":"OK","Options":"[{\"DisplayText\":\"India\",\"Value\":1},{\"DisplayText\":\"Singapore\",\"Value\":2}]"}
Country/Index gets the result from wcf service. Is there any way to strip the / in json.
Edit:
My wcf code is
List<JSONDisplayNameValue> lstLanguages = new List<JSONDisplayNameValue>();
//Get data from db.
//JSONDisplayNameValue has two variables DisplayName, Value
var json = JsonConvert.SerializeObject(lstLanguages);
return json;
Country/Index mvc code is
public JsonResult Index()
{
string Countries_list = processsvc.GetAllCountries();
return Json(new { Result = "OK", Options = Countries_list }, JsonRequestBehavior.AllowGet);
}
You are getting backslashes because you are double-serializing your data.
In your WCF code, you call JsonConvert.SerializeObject() to serialize your list of countries/languages to JSON before returning it.
In your MVC controller, you call your WCF service to get the list, which is already in JSON format. But then you add that JSON to another object and call Json() which causes the list to be serialized a second time. That is where the backslashes get added.
To fix this, you either need to
Deserialize the list you get back from your WCF service before adding it to the MVC result.
-- OR --
Make a way to retrieve your list of countries/languages without serializing it to JSON. Then add the unserialized list to your MVC result and serialize it as normal.

How to format iqueryable mvc 4 web api requests?

I'd like to use iqueryable on all my collections so that I get all of the odata features. However I need to format the response of the request with the following fields;
{
href: "url to resouce",
length: 10,
items: [
"(IQueryable results)"
]
}
Formatting the response isnt the hard part but keeping all of the odata "stuff" working is.
So my code looks like;
MyFormattedResponse.Href = "poop.com";
MyFormattedResponse.Length = 0;
MyFormattedResponse.Items = _myRepo.Gets();
Request.CreateResponse(HttpStatusCode.OK, MyFormattedResponse);
But the error I get is:
The action 'Get' on controller 'MyResource' with return type
'MyObject' cannot support querying. Ensure the type of the returned
content is IEnumerable, IQueryable, or a generic form of either
interface.
Is this something I can construct in a media formatter or perhaps a filter?
I really want to keep the odata awesomeness...
Take a look at this answer I've provided:
Web API Queryable - how to apply AutoMapper?
Your case is similar, you can do something like this:
public MyFormattedResponse Get(ODataQueryOptions<Person> query)
{
var results = query.ApplyTo(_myRepo.Gets()) as IEnumerable<Person>;
return new MyFormattedResponse() { Href = "foo.com", Length = 5, Items = results };
}
Make sure you remove the [Queryable] attribute.

How to get an object from a _ref

I apologize if this is a stupid/newb question, but when a Rally query result is returned with a _ref (using the Javascript SDK 1.32), is there a way to directly get the object associated with the _ref?
I see that I can use getRefFromTypeAndObjectId to get the type and the object ID, and then query on that type and object ID to get the object, however I wondered if there was something like getObjectFromRef or some other such way to more directly get back the object associated with the reference.
Excellent question. The getRallyObject method on RallyDataSource should do what you need.
var ref = '/defect/12345.js';
rallyDataSource.getRallyObject(ref, function(result) {
//got it
var name = result.Name;
}, function(response) {
//oh noes... errors
var errors = response.Errors;
});
In SDK 2.0 you use the load method of a data model to read a specific object. Check out this example: http://developer.help.rallydev.com/apps/2.0p5/doc/#!/guide/appsdk_20_data_models