How to remove list square brackets from serialized json string - json

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 []

Related

How to extract values from a JsonResult?

How to extract values from a JsonResult, possibly as a list of Name-Value pairs ?
Coding on ASP.Net Core 3.1
Here is my code from Controller in short:
JsonResult jsonStr = CalcPrint();
...
...
public JsonResult CalcPrint()
{
int usuage;
double bAmt
...
...
var calcResult = new { usuage, bamt = bAmt };
return Json(calcResult);
}
Debugging shows jsonStr.Value as follows:
{ usuage = 1200, bamt = 1875 }
I can assign this value to a string var and then split it; but not the right way i think.
Any other ways to get it possibly as a list ?

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);

Why am I getting Escaped Quotes? Json.net

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));

Flutter - Dart variables lost and keep getting reinitialized

I'm trying out things with Flutter right now. But my variables keep getting reinitialised when accessed from another class.
I'm using json parsing and i need two parts of my request. The "Relatorio" part and the "Mensagem" part.
to parse this json i'm doing this:
List<RelatorioProdutos> parseRelatorioPorProduto(String responseBody) {
final parsed = json.decode(responseBody);
var relatorio = parsed['Relatorio'];
var mensagem = parsed['Mensagem'];
print (mensagem); // Here the variable returns well,
//but when i need it in other class i receive null.
return relatorio.map<RelatorioProdutos>((json) => new RelatorioProdutos.fromJson(json)).toList();
}
class RelatorioProdutos {
String CodigoProduto;
var QtdVendida;
var TotalVendas;
String Descricao;
RelatorioProdutos({this.CodigoProduto, this.QtdVendida, this.TotalVendas, this.Descricao,});
factory RelatorioProdutos.fromJson(Map json) {
//returns a List of Maps
return new RelatorioProdutos(
CodigoProduto: json['CodigoProduto'] as String,
QtdVendida: json['QtdVendida'],
TotalVendas: json['TotalVendas'],
Descricao: json['Descricao'] as String,
);
}
}
I want to use this 'mensagem' variable in another class to show the error for user, but i always receive 'null'.
i already tried setState but it reloads my json and i dont want to request the RestServer again.
Thanks from now!
If I understand correctly, you want to access a local variable of a function from another class. I don't think it's possible.
One way to do it, would be to wrap your response in another object containing the response, and this variable:
List<Response<RelatorioProdutos>> parseRelatorioPorProduto(
String responseBody) {
final parsed = json.decode(responseBody);
var relatorio = parsed['Relatorio'];
var mensagem = parsed['Mensagem'];
print(mensagem); // Here the variable returns well,
//but when i need it in other class i receive null.
return relatorio
.map((json) => new Response<RelatorioProdutos>(
new RelatorioProdutos.fromJson(json), mensagem))
.toList();
}
class RelatorioProdutos {
String CodigoProduto;
var QtdVendida;
var TotalVendas;
String Descricao;
RelatorioProdutos({
this.CodigoProduto,
this.QtdVendida,
this.TotalVendas,
this.Descricao,
});
factory RelatorioProdutos.fromJson(Map json) {
//returns a List of Maps
return new RelatorioProdutos(
CodigoProduto: json['CodigoProduto'] as String,
QtdVendida: json['QtdVendida'],
TotalVendas: json['TotalVendas'],
Descricao: json['Descricao'] as String,
);
}
}
class Response<T> {
const Response(
this.value,
this.errorMessage,
);
final T value;
final String errorMessage;
bool get hasError => errorMessage != null;
}
In this example I created a Response object that can contains both the response value and an error message.
In the parseRelatorioPorProduto, instead of returning the relatorio, I changed the return type to Response<RelatorioProdutos> in order to have access to the value and the error message from any class which call this function.
Thanks Letsar, i tried yout ideia but i get a lot of others erros.
To solve this problem i used this:
List<RelatorioProdutos> parseRelatorioPorProduto(String responseBody) {
final parsed = json.decode(responseBody);
var relatorio = parsed['Relatorio'];
var mensagem = parsed['Mensagem'];
if(mensagem[0].toString().substring(16,17) == "0"){
List<RelatorioProdutos> asd = new List();
RelatorioProdutos aimeudeus = new RelatorioProdutos(Descricao: mensagem[0].toString(), CodigoProduto: "a", TotalVendas: 0, QtdVendida: 0);
asd.add(aimeudeus);
return asd;
}else{
return relatorio.map<RelatorioProdutos>((json) => new RelatorioProdutos.fromJson(json)).toList();
}
}

Can't iterate through JSON object

I'm pulling a JSON request from the politifact API:
request('http://politifact.com/api/v/2/statement/?format=[JSON]&order_by=-ruling_date&limit=1')
.then(({
data
}) => {
newArticles = extractListingsFromJSON(data);
and parsing it with a function that the JSON is passed to
function extractListingsFromJSON(json) {
var jsonObject = json.objects
Outputs entire objects array
var headline = jsonObject[0].facebook_headline
console.log("headline:\n" + headline)
Outputs headline from Objects[0]
This works as intended. However, when I try to iterate through the objects array like so:
for (var attr in jsonObject) {
console.log(attr+": "+jsonObject.facebook_headline);
}
Outputs "0: undefined"
I also tried:
console.log(attr+": "+jsonObject[facebook_headline];
Outputs nothing
As you mentioned yourself jsonObject is an array.
json.objects.forEach(function (i) {
console.log(i.facebook_headline)
})
You still need the attr key to iterate through the jsonObject. Try doing attr+" :"+jsonObject[attr].facebook_headline
instead.