Whenever i am trying to Serialize the Object with JsonConvert.SerializeObject it adds a default array name as "d"
json = JsonConvert.SerializeObject(new
{
resultsets = new List<Result>()
{
new Result { id = 1, value = "ABC", info = "ABC" },
new Result { id = 2, value = "JKL", info = "JKL" },
new Result { id = 3, value = "GSG", info = "DYU" }
}
});
return json;
The Json responce is
{
"d": "{"resultsets":[{"id":1,"value":"ABC","info":"ABC"},{"id":2,"value":"JKL","info":"JKL"},{"id":3,"value":"GSG","info":"DYU"}]}"
}
where extra array added with name "d"
i want simple array as follow
{"resultsets":[{"id":1,"value":"ABC","info":"ABC"},{"id":2,"value":"JKL","info":"JKL"},{"id":3,"value":"GSG","info":"DYU"}]}
This is to prevent direct script execution:
Suppose you were returning a plain array. The following is not a valid JS-statement:
{"d": [1]}
whereas this is:
[1]
You can find more information here:
http://encosia.com/a-breaking-change-between-versions-of-aspnet-ajax/#comment-34045
Related
I try to pass to a SSRS report, from the C# code multiple arrays of integer
var rsExec = new ReportExecutionServiceSoapClient(binding, new EndpointAddress(config.ReportExecutionUrl));
ParameterValue[] reportParam = new ParameterValue[] {
new ParameterValue { Name = "pCityId", Value = cityId.ToString() },
new ParameterValue { Name = "pDepartmentIds", Value = string.Join(",", departmentIds) },
new ParameterValue { Name = "pBuildingIds", Value = string.Join(",", buidingIds) }
};
await rsExec.SetExecutionParametersAsync(null, null, reportParam, "en-us");
as the Value type of ParameterValue is "string", it seems I have no choice but passing a CSV as parameter to the report.
Then, in the report I can use data type as integer, and say that I am passing "multiple values", but how to do it from the C# code?
PS. Related to that question
To send parameters where the Allow multiple values option is selected, you need to send a new ParameterValue object for each value that is going to be consumed by the report, all with the same Name.
In the case described above, you need to send a ParameterValue for each value in the departmentIds collection, all with the same parameter name ("pDepartmentIds").
So, if there was 3 department IDs to send, the reportParam array should contain 3 ParameterValue objects, all with the name "pDepartmentIds", one for each department ID.
ParameterValue[] reportParam = new ParameterValue[] {
new ParameterValue { Name = "pCityId", Value = cityId.ToString() },
new ParameterValue { Name = "pDepartmentIds", Value = "1" },
new ParameterValue { Name = "pDepartmentIds", Value = "2" },
new ParameterValue { Name = "pDepartmentIds", Value = "3" },
...
};
Do something similar for buildingIds.
I am insert data into .json file. My insertion works fine, but I have a problem - when I insert new data, the previous data in the file is deleted.
How can I manage that?
Also I would need it to be in the format of because I need to query it:
[
{
"Rollnumber": 3,
"StudentName": "Tapas"
},
{
"Rollnumber": 4,
"StudentName": "Papas"
}
]
When I pass the data as the list.ToArray()(that would be the _data in the code example) I get the [] brackets, but only on the first data with rollnumber = 3.
This is my code so far:
private void AddStudent()
{
Student objStudent = new Student();
objStudent.Rollnumber = 3;
objStudent.StudentName = "Tapas";
/* List<Student> _data = new List<Student>();
_data.Add(new Student()
{
Rollnumber = 4,
StudentName = "Papas"
});
*/
string jsonData = JsonConvert.SerializeObject(objStudent, Formatting.Indented);
System.IO.File.WriteAllText(jsonFileS, jsonData);
}
I have tried with the StreamWritter also, but I could not do it.
Retrieve the source file that containing JSON.
Read text content (JSON data) from source file.
Deserialize JSON data to List of student object.
Add new student student list.
Serialize the student list, you will get JSON data string as return from that method.
Save JSON string to the source file.
Here is example code:
var file = await ApplicationData.Current.LocalFolder.GetFileAsync(fileName);
var jsonString = await FileIO.ReadTextAsync(file);
var studentList = JsonConvert.DeserializeObject<List<Student>>(jsonString);
var newStudent = new Student();
newStudent.Rollnumber = 2;
newStudent.StudentName = "Abcd";
studentList.Add(newStudent);
var updatedJsonString = JsonConvert.SerializeObject(studentList);
await FileIO.WriteTextAsync(file, updatedJsonString);
I think in your situation, you can do a little trick like :
1, Read data from file
StreamReader sw = new StreamReader(fileName);
string res = sw.ReadToEnd();
2, Remove the "]" of the "res"(res variable) and add new Json string(remove the "[" and add ",") with your format.
So your string will look like two strings bellow adding together
[
{
"Rollnumber": 3,
"StudentName": "Tapas"
}
// Cut the last "]"
and
// cut the first "[" and add ","
,
{
"Rollnumber": 4,
"StudentName": "Papas"
}
]
So it will become what you want in the final :
[
{
"Rollnumber": 3,
"StudentName": "Tapas"
},
{
"Rollnumber": 4,
"StudentName": "Papas"
}
]
The answer is on this link : append to a json file
var jsonData = System.IO.File.ReadAllText(jsonFile);
// De-serialize to object or create new list
var employeeList = JsonConvert.DeserializeObject<List<Student>>(jsonData)
?? new List<Student>();
// Add any new employees
employeeList.Add(new Student()
{
Rollnumber = 1,
StudentName = "Paja1",
Subject = new Subject
{
Id = 1,
Name = "Sub1"
}
});
employeeList.Add(new Student()
{
Rollnumber = 1,
StudentName = "Pera1",
Subject = new Subject
{
Id = 1,
Name = "Sub1"
}
});
// Update json data string
jsonData = JsonConvert.SerializeObject(employeeList,Formatting.Indented);
System.IO.File.WriteAllText(jsonFile, jsonData);
As I mentioned in my comments to your question, you need to either load the entire file, deserialize it and then add items to it in memory. Once done, rewrite to the file by serializing it.
If you do not want to load the entire file into memory, then work with the file manually by manipulating the serialized string and then append to the file; else you will end up with bad JSON in file.
Here is the first method wherein you deserialize the entire file:
public static class Program
{
public static void Main()
{
var rolls = LoadRolls();
// Once the contents of the file are in memory you can also manipulate them
Roll firstRoll = rolls.SingleOrDefault(x => x.Rollnumber == 1);
if (firstRoll != null)
{
firstRoll.StudentName = "Jerry";
}
// Let's just add a few records.
rolls.AddRange(
new List<Roll>{
new Roll { Rollnumber = 1, StudentName = "Elaine" },
new Roll { Rollnumber = 2, StudentName = "George" }
});
string json = JsonConvert.SerializeObject(rolls, Newtonsoft.Json.Formatting.Indented);
File.WriteAllText("Rolls.txt", json);
Console.Read();
}
private static List<Roll> LoadRolls()
{
List<Roll> rolls = JsonConvert.DeserializeObject<List<Roll>>(File.ReadAllText("Rolls.txt"));
return rolls ?? new List<Roll>();
}
}
public class Roll
{
public int Rollnumber { get; set; }
public string StudentName { get; set; }
}
I have no problem deserializing a single json object
string json = #"{'Name':'Mike'}";
to a C# anonymous type:
var definition = new { Name = ""};
var result = JsonConvert.DeserializeAnonymousType(json, definition);
But when I have an array:
string jsonArray = #"[{'Name':'Mike'}, {'Name':'Ben'}, {'Name':'Razvigor'}]";
I am stuck.
How can it be done?
The solution is:
string json = #"[{'Name':'Mike'}, {'Name':'Ben'}, {'Name':'Razvigor'}]";
var definition = new[] { new { Name = "" } };
var result = JsonConvert.DeserializeAnonymousType(json, definition);
Of course, since result is an array, you'll access individual records like so:
string firstResult = result[0].Name;
You can also call .ToList() and similar methods on it.
You can deserialize to dynamic object by this.
dynamic result = JsonConvert.DeserializeObject(jsonArray);
One approach is to put an identifier in your JSON array string.
This code worked for me:
var typeExample = new { names = new[] { new { Name = "" } } };
string jsonArray = #"{ names: [{'Name':'Mike'}, {'Name':'Ben'}, {'Name':'Razvigor'}]}";
var result = JsonConvert.DeserializeAnonymousType(jsonArray, typeExample);
We can write 1 dimensional json-object in csharp like this
var Obj = new { username = "Test", password = "TEST" };
How would you write the two dimensional json-object, something like
var Obj = new { username: {[username:"Test", password: "TEST"]}, key:{[Key1:"OK"]} };
What you are creating is not actually a JSON object. It has nothing to do with JSON, though I can see why you thing it does based on the syntax. It is actually an anonymous type.
You can nest these types inside each other, like so (translating your example):
var Obj = new
{
username = new
{
username = "Test",
password = "TEST"
},
key = new
{
Key1 = "OK"
}
};
I have the following variable of type {Newtonsoft.Json.Linq.JArray}.
properties["Value"] {[
{
"Name": "Username",
"Selected": true
},
{
"Name": "Password",
"Selected": true
}
]}
What I want to accomplish is to convert this to List<SelectableEnumItem> where SelectableEnumItem is the following type:
public class SelectableEnumItem
{
public string Name { get; set; }
public bool Selected { get; set; }
}
I am rather new to programming and I am not sure whether this is possible. Any help with working example will be greatly appreciated.
Just call array.ToObject<List<SelectableEnumItem>>() method. It will return what you need.
Documentation: Convert JSON to a Type
The example in the question is a simpler case where the property names matched exactly in json and in code. If the property names do not exactly match, e.g. property in json is "first_name": "Mark" and the property in code is FirstName then use the Select method as follows
List<SelectableEnumItem> items = ((JArray)array).Select(x => new SelectableEnumItem
{
FirstName = (string)x["first_name"],
Selected = (bool)x["selected"]
}).ToList();
The API return value in my case as shown here:
{
"pageIndex": 1,
"pageSize": 10,
"totalCount": 1,
"totalPageCount": 1,
"items": [
{
"firstName": "Stephen",
"otherNames": "Ebichondo",
"phoneNumber": "+254721250736",
"gender": 0,
"clientStatus": 0,
"dateOfBirth": "1979-08-16T00:00:00",
"nationalID": "21734397",
"emailAddress": "sebichondo#gmail.com",
"id": 1,
"addedDate": "2018-02-02T00:00:00",
"modifiedDate": "2018-02-02T00:00:00"
}
],
"hasPreviousPage": false,
"hasNextPage": false
}
The conversion of the items array to list of clients was handled as shown here:
if (responseMessage.IsSuccessStatusCode)
{
var responseData = responseMessage.Content.ReadAsStringAsync().Result;
JObject result = JObject.Parse(responseData);
var clientarray = result["items"].Value<JArray>();
List<Client> clients = clientarray.ToObject<List<Client>>();
return View(clients);
}
I can think of different method to achieve the same
IList<SelectableEnumItem> result= array;
or (i had some situation that this one didn't work well)
var result = (List<SelectableEnumItem>) array;
or use linq extension
var result = array.CastTo<List<SelectableEnumItem>>();
or
var result= array.Select(x=> x).ToArray<SelectableEnumItem>();
or more explictly
var result= array.Select(x=> new SelectableEnumItem{FirstName= x.Name, Selected = bool.Parse(x.selected) });
please pay attention in above solution I used dynamic Object
I can think of some more solutions that are combinations of above solutions. but I think it covers almost all available methods out there.
Myself I use the first one
using Newtonsoft.Json.Linq;
using System.Linq;
using System.IO;
using System.Collections.Generic;
public List<string> GetJsonValues(string filePath, string propertyName)
{
List<string> values = new List<string>();
string read = string.Empty;
using (StreamReader r = new StreamReader(filePath))
{
var json = r.ReadToEnd();
var jObj = JObject.Parse(json);
foreach (var j in jObj.Properties())
{
if (j.Name.Equals(propertyName))
{
var value = jObj[j.Name] as JArray;
return values = value.ToObject<List<string>>();
}
}
return values;
}
}
Use IList to get the JArray Count and Use Loop to Convert into List
var array = result["items"].Value<JArray>();
IList collection = (IList)array;
var list = new List<string>();
for (int i = 0; i < collection.Count; j++)
{
list.Add(collection[i].ToString());
}