Why am I getting Escaped Quotes? Json.net - json

I am not sure if I am doing this right. I got json stored in my database that I want to update.
var items = dbContext.items.FromSql("select *, JSON_VALUE(Attributes, '$.serialNumber') as serialNumber FROM Items WHERE JSON_VALUE(Attributes,'$.serialNumber') like '%15830792087%'").ToList();
var attributes = JObject.Parse(items[0].Attributes);
var images = attributes["image"];
if(images == null){
var newImage = new List<InventoryImage>()
{
new InventoryImage()
{
ImageUrl = imageBlob.Uri.AbsoluteUri,
OrignalName = file.FileName,
ThumbnailUrl = thumbnailBlob.Uri.AbsoluteUri
}
};
JProperty newProp = new JProperty("image", JsonConvert.SerializeObject(newImage));
attributes.Add(newProp);
images[0].Attributes = JsonConvert.SerializeObject(attributes);
dbContext.SaveChanges();
}
what I get in my db.
"image":"[{\"OrignalName\":\"cat-pet-animal-domestic-104827.jpeg\",\"ImageUrl\":\"ed1ab040e710.jpeg\",\"ThumbnailUrl\":\"3c3e73e3-5062-492b-b830-ed1ab040e710_thumbnail.jpeg\"}]"}

JProperty newProp = new JProperty("image", JsonConvert.SerializeObject(newImage));
This will serialize newImage into a JSON string and then assign that JSON string as the value to the image property. So the value of property is a string which happens to be a JSON string.
What you should do instead is assign the value directly without serializing it first. That way you avoid a double serialization:
Property newProp = new JProperty("image", JToken.FromObject(newImage));

Related

How to remove list square brackets from serialized json string

I'm calling a stored procedure using a controller.
var insert_query = entities.Database.SqlQuery<Call_Info>("exec [dbo].[insert_call_info] #call_id",
new SqlParameter("call_id", call_id)).ToList();
jsonResult = JsonConvert.SerializeObject(insert_query); // <-- using Newtonsoft.Json
The json string is the following:
"[{\"call_info_id\":18,\"call_id\":91389,\"user_id\":\"105bdbfb-d65a-42d3-ac79-c1e2575ed243\",\"call_arrive\":\"2020-04-03T21:51:24.797\",\"call_end\":\"2020-04-03T22:04:24.797\",\"info\":\"test\",\"AspNetUser\":null,\"Call\":null,\"StatusCode\":1}]"
Is there a way to remove the [ and ] brackets?
I want the json string to be:
{\"call_info_id\":18,\"call_id\":91389,\"user_id\":\"105bdbfb-d65a-42d3-ac79-c1e2575ed243\",\"call_arrive\":\"2020-04-03T21:51:24.797\",\"call_end\":\"2020-04-03T22:04:24.797\",\"info\":\"test\",\"AspNetUser\":null,\"Call\":null,\"StatusCode\":1}
var insert_query = entities.Database.SqlQuery<Call_Info>("exec [dbo].[insert_call_info] #call_id",
new SqlParameter("call_id", call_id)).ToList();
if(insert_query!=null && insert_query.Count()>0)
{
jsonResult = JsonConvert.SerializeObject(insert_query[0]);
}
This will serialise only 1st element so it wont have []

How do I consume a JSon object that has no headers?

My C# MVC5 Razor page returns a Newtonsoft json link object to my controller (the "1" before \nEdit |" indicates that the checkbox is checked:
"{\"0\": [\"6146\",\"Kimball\",\"Jimmy\",\"General Funny Guy\",\"277\",\"Unite\",\"Jun 2019\",\"\",\"\",\"1\",\"\nEdit |\nDetails\n\n \n\"],\"1\": [\"6147\",\"Hawk\",\"Jack\",\"\",\"547\",\"Painters\",\"Jun 2019\",\"\",\"\",\"on\",\"\nEdit |\nDetails\n\n \n\"]}"
How do I parse this?
I am using a WebGrid to view and I want to allow the users to update only the lines they want (by checking the checkbox for that row), but it doesn't include an id for the 's in the dom. I figured out how to pull the values, but not the fieldname: "Last Name" , value: "Smith"... I only have the value and can't seem to parse it... one of my many failed attempts:
public ActoinResult AttMods(string gridData)
{
dynamic parsedArray = JsonConvert.DeserializeObject(gridData);
foreach (var item in parsedArray)
{
string[] itemvalue = item.Split(delimiterChars);
{
var id = itemvalue[0];
}
}
I finally sorted this one out..If there is a more dynamic answer, please share... I'll give it a few days before I accept my own (admittedly clugy) answer.
if(ModelState.IsValid)
{
try
{
Dictionary <string,string[]> log = Newtonsoft.Json.JsonConvert.DeserializeObject<Dictionary<string, string[]>>(gridData);
foreach (KeyValuePair<string,string[]> keyValue in log)
{
if (keyValue.Value[9] == "1")//Update this row based on the checkbox being checked
{
var AttendeeID = keyValue.Value[0];
int intAttendeeID = 0;
if (int.TryParse(AttendeeID, out intAttendeeID))//Make sure the AttendeeID is valid
{
var LName = keyValue.Value[1];
var FName = keyValue.Value[2];
var Title = keyValue.Value[3];
var kOrgID = keyValue.Value[4];
var Org = keyValue.Value[5];
var City = keyValue.Value[7];
var State = keyValue.Value[8];
var LegalApproval = keyValue.Value[9];
tblAttendee att = db.tblAttendees.Find(Convert.ToInt32(AttendeeID));
att.FName = FName;
att.LName = LName;
att.Title = Title;
att.kOrgID = Convert.ToInt32(kOrgID);
att.Organization = Org;
att.City = City;
att.State = State;
att.LegalApprovedAtt = Convert.ToBoolean(LegalApproval);
}
}
}
db.SaveChanges();
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
You can avoid assigning the var's and just populate the att object with the KeyValue.Value[n] value, but you get the idea.

how to parse string object without double quote in front in json

i have an array in my angular applicaton for eg:
searchTerm : any[]
I have a textbox with a value {'state':'tn'} and want to push this to the searchTerm array. Currently i add this item to a service and then array as:
private onItemAdded(event): void {
const filter = JSON.parse('"' + event['value'] + '"');
this.dataService.addFilter(filter);
}
But it is storing as "{'state':'tn'}"
How can i parse this without double quotes in the front?
console.log('ADDED FILTER', event['value']);
here the value is printed as {'state':'value'}
but when assign to variable as below, it adds double quotes
let filter = event['value'];
Thanks
why you are using parse?, it is for converting from JSON to object, instead use stringify which will parse your object to JSON(string)
const obj = "{'state':'tn'}";
let filter = JSON.stringify(obj);
filter = filter.slice(1, filter.length - 1);
console.log(filter);

Json.NET deserializing object always shows null

JsonConvert.DeserializeObject<> not working .
Always getting null.
Json.NET deserializing object returns null.
Here is the code:
JsonResult jsonresult = Json(result1, JsonRequestBehavior.AllowGet);
User _contacts = new User();
_contacts = JsonConvert.DeserializeObject<User>(jsonresult.Data.ToString());
In jsonresult.Data.ToString():
{"recordsTotal":13,"recordsFiltered":13,"data":[{"Id":2,"Title":"Brajo testing","Type":null,"Description":null,"Importancy":null,"CreatedDate":"2017-03-16T14:31:04.41","Status":null,"Email":"+HNcbJGxLqAGmAQq9gOW1A==","Name":"Oliver Woodss"},{"Id":3,"Title":"udal testing","Type":null,"Description":null,"Importancy":null,"CreatedDate":"2017-03-16T14:31:41.253","Status":null,"Email":"+HNcbJGxLqAGmAQq9gOW1A==","Name":"Oliver Woodss"},
When i assign this comes null.
result = this.Json(new { draw = draw, recordsFiltered = recordsTotal, recordsTotal = recordsTotal, data = _contacts }, JsonRequestBehavior.AllowGet);
Do like this,
var response = client.GetAsync(apiUrl).Result;
var responseResult = JsonConvert.DeserializeObject<List<User>>
(response.Content.ReadAsStringAsync().Result);
Then you can fetch data from responseResult with a dot operator.

Convert SqlCommand Output to List<MyType>?

I am using an ADO.NET SqlCommand with a single SqlDbType.Structured parameter to send a table-valued parameter to a sproc. The sproc returns many rows, which I need to get into a strongly-Typed List of . What is the best way to convert the result set (whether DataTable from a DataAdapter or DataReader bits) into List?
Thanks.
You can use LINQ with a DataReader:
var list = reader.Cast<IDataRecord>()
.Select(dr => new YourType { Name = dr.GetString(0), ... })
.ToList();
The most efficient way is using datareader:
var items = new LinkedList<MyClass>();
using(var connection = GetConnection()) {
using(var cmd = connection.CreateCommand()){
cmd.CommandText = "... your SQL statement ...";
// ... add parameters
cnn.Open();
using(var reader = cmd.ExecuteReader()) {
// accessing values via number index is most efficient
//gets index of column with name "PrimaryKey"
var ndxPrimaryKey = reader.GetOrdinal("PrimaryKey");
var ndxColumn1 = reader.GetOrdinal("Column1");
var ndxColumn2 = reader.GetOrdinal("Column2");
while(reader.Read()) {
var item = new MyClass();
// returns value of column "PrimaryKey" typed to nullable Guid
item.PrimaryKey = reader.GetValue(ndxPrimaryKey) as Guid?;
item.Column1 = reader.GetValue(ndxColumn1) as string;
item.Column2 = reader.GetValue(ndxColumn2) as int?;
items.AddLast(item);
}
}
cnn.Close();
}
}
return items;
i think you can use Dapper to convert a query to a class.
for more information see my answer in this link