ASP.NET MVC 3 controller failed to receive a json 2D array - json

Not sure if it is a bug or not. I followed some tutorial to post a Json 2D array to a ASP.NET MVC controller, and it works fine when the first element of the array is not empty, otherwise it fails.
Example: If my json obj is
var obj = {
ItemsArr: [[1, 2],[]] // first element is an array with a few elements
};
The controller will receive the data correctly. However if the first element of the 2D array is an empty array, like:
var obj = {
ItemsArr: [[], [1, 2]] // first element is an EMPTY array
};
the controller will receive a null.
I'm using jquery.json-2.3.min.js to convert objs to json strings.
The converted strings look fine:
{"ItemsArr":[[1,2],[]]}
{"ItemsArr":[[],[1,2]]}
The model code:
public class Model
{
public List<string[]> ItemsArr {get;set;}
}
public MyController : Controller
{
public ActionResult DoSomething( Model model )
{ ...
}
}
Have anyone met this problem? Any idea to solve it?
Thanks in advance!
===================================
Edit:
After some research, if I changed the empty array to null, it works.
{"ItemsArr":[null,[1,2]]}

I would suggest passing a array of objects and create a class with the Same properties on The server side, asp.net MVC will then automatically convert this array (on the JS end) into a list (or any other IEnumerable) that is a part of the action signature.

Related

How to convert JSON Array of Objects to Observable Array in angular

I am calling a rest API from angular, the rest api returns data in JSON Array of Objects like this
Now I am trying to convert it to my model class array but don't getting anywhere can you please guide me.
My Model Class
My Service File
Here it gives error on map and I don't know how to convert it to my model class array to display it in table
Resolved It.
As i was directly getting the array of objects in response, I don't need to convert it and use an interface. So here is my correct code
fetchAllGamesRecord() : Observable<Fifa[]>{
const fifaUrl = `${this.baseUrl}/fetchAllGamesRecord`;
return this.httpClient.get<Fifa[]>(fifaUrl);
}
This function is called like this
this.fifaService.fetchAllGamesRecord().subscribe(
data => {
this.allGameRecord = data;
console.log(`Data = `+data);
}
);
you can do that while calling fetchAllGamesRecord
fetchAllGamesRecord().subscribe( (response: Fifa[]) => {
// do something
}
where Fifa is interface not class
In the Spring framework also Fifa[] doesn't work in REST calls, we need to put it in another class as I showed below, I assume this will work.
export class FifaWrapper {
wrapper: Fifa[];
}
and also use this class in Observable
fetchAllGamesRecord(): Observable<FifaWrapper> {
... do you handling here
}

deserialize json to object in netstandard1.0

I am trying to serialize a string that is returned from a http response and I am using netstandard1.0. Not a lot of serializing functions work in this framework, but I finally found a working function. Here is my code so far:
HttpResponseMessage Response = // initialized else where
var jsonTask = Response.Content.ReadAsStringAsync();
if (!jsonTask.IsCompleted) jsonTask.RunSynchronously();
string json = jsonTask.Result;
Data = JsonConvert.DeserializeObject<MyModel>(json);
However this does not deserialize I get from the http response. It throws an error that the DeserializeObject function is looking for a different format. When I run Result.Content.ReadAsStringAsync(), I get the result in the following format.
"[{\"key\":\"Password\",\"errors\":[\"The Password field is required.\"]},{\"key\":\"UserName\",\"errors\":[\"The UserName field is required.\"]},{\"key\":\"OrganizationUserName\",\"errors\":[\"The OrganizationUserName field is required.\"]}]"
Does anyone know how to deserialize this format?
If you define your MyModel as follows:
public class MyModel
{
public string key { get; set; }
public List<string> errors { get; set; }
}
You can deserialize as follows:
var list = JsonConvert.DeserializeObject<List<MyModel>>(json);
Notes:
I generated the c# definition for MyModel by uploading your JSON to http://json2csharp.com/.
The reason for the exception you are seeing trying to deserialize directly to MyModel is that your outer JSON container is an array, not an object. As explained in the standard, JSON has two types of container:
An array which is an ordered collection of values. An array begins with [ (left bracket) and ends with ] (right bracket). Values are separated by , (comma).
An object which is an unordered set of name/value pairs. An object begins with { (left brace) and ends with } (right brace).
In the Json.NET Serialization Guide: IEnumerable, Lists, and Arrays it is explained that JSON arrays are converted from and to .Net types implementing IEnumerable. So that's what you need to do.
If you know the array will contain no more than one element, you can use SingleOrDefault() to extract that single element:
Data = list.SingleOrDefault();
However, in the example included in you question, the outer array has 3 items, so this is not appropriate.
Sample fiddle.

DataType for exposing data as json in mvc model

how can I introduce new property into my mvc model which will hold this cities json data.
public ActionResult Edit(int id)
{
MyModel model = repository.GetById(id);
if (model.CountryId.HasValue)
{
// load cities into new property
}
return this.View(result);
}
what data type should be my property (Cities) if I want to be exposed as json on client side for further js manipulation? ICollection? Is there any recommendation for this?
Set them up as any object type you like:
MyModel model = repository.GetById(id);
if (model.CountryId.HasValue)
{
model.Cities = repository.GetCities(model.CountryId.Value);
}
return this.View(model);
Then, on the client, you can use Json.NET library to serialize it. I use this trick when I'm trying to pass an array to a client-side JS component; essentially, it serializes the array of objects into a client-side array:
#(Html.Raw(Newtonsoft.Json.JsonConvert.SerializeObject(Model.Cities))
Whatever type of object represents each city is what determines what gets rendered out to the client; it simply reads the object and renders an equivalent JS object with all the same properties. You can fine tune that by saying:
Model.Cities.Select(i => new { i.ID, i.Name, .. })
Which only includes a subset. There are also attributes you can use to exclude certain columns I believe.

Spring json #ResponseBody - return a named variable

I have a Spring controller method that is correctly returning a collection of objects in the JSON to the client:
#RequestMapping(value="/admin/rawreads/unknowntags", method=RequestMethod.GET)
public #ResponseBody Collection<RawRead> getRawReadsWithUnknownTag() {
....
}
I'm trying to integrate a jQuery addon/plugin called DataTables. DataTables can handle the asynchronous request to fetch data and populate a table in the page for me, however it requires the data to be return in an array with a specific name "aaData" rather than the current format of :
[{"oid":149452,"date":1233076733000,"readerId":"811210008","recordNo":226,"tagCode":"0103A003C0","reader":null,"guard":null,"checkpoint":null},{"oid":149453,"date":1233076734000,"readerId":"8112100 .... etc]
Suggested return format for DataTables from the DataTable docs:
{
"sEcho": 1,
"iTotalRecords": "n",
"iTotalDisplayRecords": "n",
"aaData": [
[object1][object2].... etc
]
}
How can I change my Java method to return data in the format DataTables needs - a named array?
EDIT:
Tried putting vars into a HashMap serverside, gets a bit closer to what I need:
{"iTotalDisplayRecords":3050,"iTotalRecords":3050,"aaData":
[{"oid":149452,"date":1233076733000, ...<snip>},{...}]
}
Make a separate class in the correct format for data tables, having fields for sEcho, itotalrecords, ittotaldisplayrecords and then an array called aaData.
Then return this class via jason and that is then in your suggested format.
class TableDTO
{
int sEcho;
int iTotalRecords;
int itotalDisplayRecords;
array[] aaData;
}
Obviously assign data to these fields and proper accessors etc!
You must write one more TotalDisplayRecords class and it must incluse array oid class. After that, you return TotalDisplayRecords object.

Create JSON Request string using Javascript Overlay types in GWT

We have used JSO for our JSON parsing in GWT client side. Now, we need to convert our Java objects to JSON string. I just wanted to understand, how we can achieve this? JSO overlay types was used for JSON parsing. Can it also be used to create a JSON request string or do we have to go by some other means?
Generating a JSON object in JavaScript is pretty simple. You can do it like this:
var obj = { "var1": "hello", "var2": "world" };
this will generate a JSON object with two varibles ("var1" and "var2") with their values ("hello", "world").
The Object can be converted into a String (for sending purposes) with the JSON.stringify(jso); method.
Generating JSON data from the java code isn't possible (well not with a usefull result) since all varibles are optimzed to single Strings, so applying this method wouldn't hava a usefull result (if even possible).
If you have already a JSO object (generated with something like safeeval). You can edit your varibles there, like this:
public final native void newValue(String newValue) /*-{
this.ValueName = newValue;
}-*/;
If you then want the object as string you have to define the following method in your JSO class:
public final native String returnAsString () /*-{
return JSON.stringify(this);
}-*/;
or use this in you Java class: String s = (new JSONObject(jso)).toString();.
This way you can edit your original intput data and send the original object back to the server.
BR