JSON deserialize throws exception - c#

I have a C# code that defines a constant JSON string and a corresponding POCO class. however i get an exception:
The JSON value could not be converted Path: $ | LineNumber: 0 | BytePositionInLine: 1.
Code
try
{
var filters = JsonSerializer.Deserialize <CmsContactsFilter>(FilterJson);
}
catch(Exception ex)
{
}
JSON
#"[{""cms"":""us-its"",""group"":[""ciso"",""cloudAdminsDistributionList"",""cloudAdmins""]},""cms"":""us-csdaudit"",""abc"":[""biso"",""costManagement""]},]";
POCO Class
public class CmsContactsFilter
{
public string Cms { get; set; }
public List<string> Group { get; set; }
}

Your json is not valid, here is the valid version of your json:
[
{
"cms": "us-its",
"group": [
"ciso",
"cloudAdminsDistributionList",
"cloudAdmins"
]
},
{
"cms": "us-csdaudit",
"group": [
"biso",
"costManagement"
]
}
]
Your code should be looks like this:
using System.Text.Json;
string filterJson = System.IO.File.ReadAllText("data.json");
var filters = JsonSerializer.Deserialize<List<CmsContactsFilter>>(filterJson);
foreach (var item in filters)
{
Console.WriteLine(item.cms+":");
foreach (var y in item.group)
{
Console.WriteLine("----"+y);
}
}
public class CmsContactsFilter
{
public string cms { get; set; }
public List<string> group { get; set; }
}
the name of the properties of the the CmsContactsFilter should be same with your json attributes names. if they are in lower-case format, your attribute name in the C# should be in the lower-case too.

your json is not valid, you need to add { to the second array item, and use an object collection for deserialization
var FilterJson = #"[{""cms"":""us-its"",""group"":[""ciso"",""cloudAdminsDistributionList"",""cloudAdmins""]},{""cms"":""us-csdaudit"",""abc"":[""biso"",""costManagement""]}]";
var filters = System.Text.Json.JsonSerializer.Deserialize <List<CmsContactsFilter>>(FilterJson);
and fix class
public class CmsContactsFilter
{
public string cms { get; set; }
public List<string> group { get; set; }
public List<string> abc { get; set; }
}
but as I understand your array has much more objects then 2. So you can try this code for the big json with different array names (if you had used Newtonsoft.Json this code could be significanly simplier)
JsonArray array = JsonNode.Parse(FilterJson).AsArray();
List<CmsContactsFilter> filters = new List<CmsContactsFilter>();
foreach (JsonObject item in array)
{
var obj = new CmsContactsFilter();
foreach (var prom in item.AsObject())
{
var name = prom.Key;
if (name == "cms")
{
obj.cms = prom.Value.ToString();
continue;
}
obj.groupName = name;
obj.group = System.Text.Json.JsonSerializer.Deserialize<List<string>>(prom.Value.ToString());
}
filters.Add(obj);
}
}
class
public class CmsContactsFilter
{
public string cms { get; set; }
public string groupName { get; set; }
public List<string> group { get; set; }
}

Related

custom response object for model validation in asp.net core

I want custom object in response of API having [required] data annotation on model properties like this:
{
"resourceType": "OperationOutcome",
"issue": [
{
"severity": "fatal",
"code": "required",
"location": [
"/f:AllergyIntolerance/f:status"
]
}
]
}
Is it possible to do it or I would have to code it.
Because model validation happens before action is called, is there any way I can do it?
To create custom request and respond samples for your api, you can use Swashbuckle.AspNetCore.Swagger and to improve validations on your models you can use FluentValidations Sample. Good Luck!
first for simplify define your models like these :
public class ResponseModel
{
public string resourceType { get; set; }
public List<ResponseIssueModel> issue { get; set; } = new List<ResponseIssueModel>();
}
public class ResponseIssueModel
{
public string severity { get; set; }
public string code { get; set; }
public List<string> locations { get; set; } = new List<string>();
}
Then on your actions you can return this :
var response = new ResponseModel();
response.resourceType = "OperationOutcome";
response.issue.Add(new ResponseIssueModel
{
severity = "fatal",
code = "required",
locations = { "/f:AllergyIntolerance/f:status" }
});
return Ok(response);
you can use Builder Pattern for easy create response object
If you want to validate your model in controller,you could try with TryValidateModel method as mentioned in the document:
I tried as below:
in controller:
var model = new TestModel() { Id=1,nestedModels=new List<NestedModel>() { new NestedModel() { Prop1="P11"} } };
var isvalid=TryValidateModel(model);
var errorfiledlist = new List<string>();
if (!isvalid)
{
foreach (var value in ModelState.Values)
{
foreach (var error in value.Errors)
{
errorfiledlist.Add(MidStrEx(error.ErrorMessage,"The "," field"));
}
}
}
var jsonstring = JsonSerializer.Serialize(model);
foreach (var field in errorfiledlist)
{
var oldstr = String.Format("\"{0}\":null", field);
var newstr = String.Format("\"{0}\":\"required\"", field);
jsonstring = jsonstring.Replace(oldstr, newstr);
};
var obj = JsonSerializer.Deserialize<Object>(jsonstring);
return Ok(obj);
MidStrEx method:
public static string MidStrEx(string sourse, string startstr, string endstr)
{
string result = string.Empty;
int startindex, endindex;
try
{
startindex = sourse.IndexOf(startstr);
if (startindex == -1)
return result;
string tmpstr = sourse.Substring(startindex + startstr.Length);
endindex = tmpstr.IndexOf(endstr);
if (endindex == -1)
return result;
result = tmpstr.Remove(endindex);
}
catch (Exception ex)
{
}
return result;
}
Models:
public class TestModel
{
public int Id { get; set; }
[Required]
public string Prop { get; set; }
public List<NestedModel> nestedModels { get; set; }=new List<NestedModel>();
}
public class NestedModel
{
public string Prop1 { get; set; }
[Required]
public string Prop2 { get; set; }
}
The result:

How to extract data from JSON array

I know its an array, but I am completely new to JSON and need help comprehending how this is structured, here is my attempt at extracting data:
String JSonString = readURL("//my URL is here");
JSONArray s = JSONArray.fromObject(JSonString);
JSONObject Data =(JSONObject)(s.getJSONObject(0));
System.out.println(Data.get("RecycleSiteUrl"));
I want to extract RecycleSiteUrl based on SiteId
My JSON data that I have goes like this :
[
{
"SiteId": 1,
"RecycleLogoUrl": "https://static-contrado.s3-eu-west- 1.amazonaws.com/cms/recyclecarelabel/d867c499-abc0-4ade-bc1a-f5011032c3e0132901511939451201.jpeg",
"RecycleSiteUrl": "bagsoflove.co.uk/recycling",
"Culture": "en-GB"
},
{
"SiteId": 10,
"RecycleLogoUrl": "https://static-contrado.s3-eu-west-1.amazonaws.com/cms/recyclecarelabel/95d28588-33e3-420c-8b24-4a8095c0f6ac132901511364264751.jpeg",
"RecycleSiteUrl": "contrado.co.uk/recycling",
"Culture": "en-GB"
}]
I dont really have a strong grasp of this stuff so all the help is appreciated.
you can try this, it doesn't need to create any classes
var jsonParsed=JArray.Parse(json);
var siteId=10;
var recycleSiteUrl = GetRecycleSiteUrl(jsonParsed,siteId); // contrado.co.uk/recycling
public string GetRecycleSiteUrl(JArray jArray, int siteId)
{
return jArray.Where(x=> (string) x["SiteId"] == siteId.ToString()).First()["RecycleSiteUrl"].ToString();
}
or using json path
string recycleSiteUrl= (string)jsonParsed
.SelectToken("$[?(#.SiteId=="+siteId.ToString()+")].RecycleSiteUrl");
using Newtonsoft.Json;
using System.Linq;
public void Method()
{
var yourSearchParameter = 10;
string jsonStr = readURL("//my URL is here");
var obj = JsonConvert.DeserializeObject<List<RecycleSite>>(jsonStr);
var siteUrl = obj.SingleOrDefault(q => q.SiteId == yourSearchParameter).RecycleSiteUrl;
/* Do something with the siteUrl */
}
public class RecycleSite
{
public int SiteId { get; set; }
public string RecycleLogoUrl { get; set; }
public string RecycleSiteUrl { get; set; }
public string Culture{ get; set; }
}
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
public Class Site
{
public string GetRecycleSiteUrl(int siteId, string jsonArray)
{
var siteInfos = JsonConvert.DeserializeObject<List<SiteInfo>>(jsonArray);
string recycleSiteUrl = siteInfos.FirstOrDefault(info => info.SiteId == siteId).RecycleSiteUrl;
return recycleSiteUrl;
}
}
public class SiteInfo
{
public int SiteId { get; set; }
public string RecycleLogoUrl { get; set; }
public string RecycleSiteUrl { get; set; }
public string Culture { get; set; }
}
You can create Site object and access GetRecycleSiteUrl method by passing respective parameter values.

Converting JSON array

I am attempting to use the Newtonsoft JSON library to parse a JSON string dynamically using C#. In the JSON is a named array. I would like to remove the square brackets from this array and then write out the modified JSON.
The JSON now looks like the following. I would like to remove the square bracket from the ProductDescription array.
{
"Product": "123",
"to_Description": [
{
"ProductDescription": "Product 1"
}
]
}
Desired result
{
"Product": "123",
"to_Description":
{
"ProductDescription": "Product 1"
}
}
I believe I can use the code below to parse the JSON. I just need some help with making the modification.
JObject o1 = JObject.Parse(File.ReadAllText(#"output.json"));
The to_Description property starts off as List<Dictionary<string,string>> and you want to take the first element from the List.
So, given 2 classes
public class Source
{
public string Product {get;set;}
public List<Dictionary<string,string>> To_Description{get;set;}
}
public class Destination
{
public string Product {get;set;}
public Dictionary<string,string> To_Description{get;set;}
}
You could do it like this:
var src = JsonConvert.DeserializeObject<Source>(jsonString);
var dest = new Destination
{
Product = src.Product,
To_Description = src.To_Description[0]
};
var newJson = JsonConvert.SerializeObject(dest);
Note: You might want to check there really is just 1 item in the list!
Live example: https://dotnetfiddle.net/vxqumd
You do not need to create classes for this task. You can modify your object like this:
// Load the JSON from a file into a JObject
JObject o1 = JObject.Parse(File.ReadAllText(#"output.json"));
// Get the desired property whose value is to be replaced
var prop = o1.Property("to_Description");
// Replace the property value with the first child JObject of the existing value
prop.Value = prop.Value.Children<JObject>().FirstOrDefault();
// write the changed JSON back to the original file
File.WriteAllText(#"output.json", o1.ToString());
Fiddle: https://dotnetfiddle.net/M83zv3
I have used json2csharp to convert the actual and desired output to classes and manipulated the input json.. this will help in the maintenance in future
First defined the model
public class ToDescription
{
public string ProductDescription { get; set; }
}
public class ActualObject
{
public string Product { get; set; }
public List<ToDescription> to_Description { get; set; }
}
public class ChangedObject
{
public string Product { get; set; }
public ToDescription to_Description { get; set; }
}
Inject the logic
static void Main(string[] args)
{
string json = "{\"Product\": \"123\", \"to_Description\": [ { \"ProductDescription\": \"Product 1\" } ]} ";
ActualObject actualObject = JsonConvert.DeserializeObject<ActualObject>(json);
ChangedObject changedObject = new ChangedObject();
changedObject.Product = actualObject.Product;
changedObject.to_Description = actualObject.to_Description[0];
string formattedjson = JsonConvert.SerializeObject(changedObject);
Console.WriteLine(formattedjson);
}
Why not:
public class EntityDescription
{
public string ProductDescription { get; set; }
}
public class Entity
{
public string Product { get; set; }
}
public class Source : Entity
{
[JsonProperty("to_Description")]
public EntityDescription[] Description { get; set; }
}
public class Target : Entity
{
[JsonProperty("to_Description")]
public EntityDescription Description { get; set; }
}
var raw = File.ReadAllText(#"output.json");
var source = JsonConvert.DeserializeObject<Source>(raw);
var target = new Target { Product = source.Product, Description = source.Description.FirstOrDefault() };
var rawResult = JsonConvert.SerializeObject(target);
Update For dynamic JSON
var jObject = JObject.Parse(File.ReadAllText(#"output.json"));
var newjObject = new JObject();
foreach(var jToken in jObject) {
if(jToken.Value is JArray) {
List<JToken> l = jToken.Value.ToObject<List<JToken>>();
if(l != null && l.Count > 0) {
newjObject.Add(jToken.Key, l.First());
}
} else {
newjObject.Add(jToken.Key, jToken.Value);
}
}
var newTxt = newjObject.ToString();

Reading JSON file with Array

I'm currently working on JSON string extraction using C#. My JSON string consist of an array with repetitive keys. Not sure if I'm describing it right since I'm new to this.
This is my JSON string
{"Index":
{ "LibraryName":"JGKing"
, "FormName":"AccountsPayable"
, "User":null
, "FilingPriority":null
, "FileDescription":null
, "Fields":
{"Field":
[
{ "Name":"invItemID"
, "Value":"6276"
}
,{ "Name":"invEntityCode"
, "Value":"16"
}
,{ "Name":"invVendorCode"
, "Value":"MIRUB01"
}
,{ "Name":"invNumber"
, "Value":"PWD5"
}
,{ "Name":"invDate"
, "Value":"2017-08-21"
}
,{ "Name":"invStatus"
, "Value":""
}
,{ "Name":"invCurrencyCode"
, "Value":"AU"
}
,{ "Name":"invCurrencyRate"
, "Value":"1"
}
,{ "Name":"invTax"
, "Value":"454.3"
}
, {"Name":"invTotal"
, "Value":"4997.27"
}
, {"Name":"invReceivedDate"
, "Value":"2017-09-06"
}
,{ "Name":"InvoiceLine1"
, "Value":"{\r\n \"invLineNumber\": \"1\",\r\n \"invPONumber\": \"\",\r\n \"invPOLineNo\": \"1\",\r\n \"invPOJobID\": \"\",\r\n \"invCostCode\": \"\",\r\n \"invCategory\": \"\",\r\n \"invGLCode\": \"61-01-49-6862.517\",\r\n \"invDescription\": \"\",\r\n \"invEntryType\": \"\",\r\n \"invAmount\": \"4542.97\",\r\n \"invTaxAmount\": \"454.3\",\r\n \"invTaxCode\": \"GST\",\r\n \"invAmountIncTax\": \"4997.27\"\r\n}"}]}}}
I need to extract the value of invItemID key which is inside the array.
I tried to serialize my json string from a class but it returns null in the List<>
Here's my code
public void CFExport(string jsonFile)
{
string ItemIDField;
string ItemIDValue;
using (StreamReader r = new StreamReader(jsonFile))
{
JsonSerializer s = new JsonSerializer();
var Idx = (JSONMain)s.Deserialize(r, typeof(JSONMain));
var flds = (Fields)s.Deserialize(r, typeof(Fields));
if (flds != null)
{
foreach (var _field in flds.Field)
{
ItemIDField = _field.Name;
ItemIDValue = _field.Value;
}
}
}
}
public class JSONMain
{
public Index Index { get; set; }
}
public class Index
{
public string LibraryName { get; set; }
public string FormName { get; set; }
public string User { get; set; }
public string FilingPriority { get; set; }
public string FileDescription { get; set; }
}
public class Fields
{
public List<Field> Field { get; set; }
}
public class Field
{
public string Name { get; set; }
public string Value { get; set; }
}
I hope you can help me.
Thanks in advance
Try to reflect the JSON file with your classes like this:
public class Index
{
public string LibraryName { get; set; }
public string FormName { get; set; }
public string User { get; set; }
public string FilingPriority { get; set; }
public string FileDescription { get; set; }
public Fields Fields { get; set; } //this line makes the difference
}
If you deserialize now, the fields should be populated automatically. I also advice you to use JsonConvert.Deserialze<>() since it is a bit easier (see documentation) and you are new to this topic.
Getting the value of invItemID could look like this:
public void CFExport(string jsonFile)
{
string ItemIDField = "invItemID";
string ItemIDValue;
using (StreamReader r = new StreamReader(jsonFile))
{
var Idx = JsonConvert.DeserializeObject<JSONMain>(r);
foreach(var field in Idx.Index.Fields.Field)
{
if(field.Name == ItemIDField)
{
ItemIDValue = field.Value;
}
}
}
}
Whoohoo. My first answer on Stackoverflow! I hope this helps you.
I need to extract the value of invItemID key which is inside the array.
You can retrieve value for your specified key invItemID from Field array by using JObject.
So you have no more need to manage classes for your json.
Here i created a console app for your demonstration purpose.
class Program
{
static void Main(string[] args)
{
//Get your json from file
string json = File.ReadAllText(#"Your path to json file");
//Parse your json
JObject jObject = JObject.Parse(json);
//Get your "Field" array to List of NameValuePair
var fieldArray = jObject["Index"]["Fields"]["Field"].ToObject<List<NameValuePair>>();
//Retrieve Value for key "invItemID"
string value = fieldArray.Where(x => x.Name == "invItemID").Select(x => x.Value).FirstOrDefault();
//Print this value on console
Console.WriteLine("Value: " + value);
Console.ReadLine();
}
}
class NameValuePair
{
public string Name { get; set; }
public string Value { get; set; }
}
Output:

JSON Parser Element not found

This is my JSON
{
"State of Origin 2014":{
"1471137":{
"EventID":1471137,
"ParentEventID":1471074,
"MainEvent":"State Of Origin Series 2014",
"Competitors":{
"ActiveCompetitors":3,
"Competitors":[
{
"Team":"New South Wales (2 - 1)",
"Win":"2.15",
},
{
"Team":"New South Wales (3 - 0)",
"Win":"3.05",
},
{
"Team":"Queensland (2 - 1)",
"Win":"3.30",
}
],
"TotalCompetitors":3,
"HasWinOdds":true
},
"EventStatus":"Open",
"IsSuspended":false,
"AllowBets":true
},
"3269132":{
"EventID":3269132,
"ParentEventID":0,
"MainEvent":"New South Wales v Queensland",
"Competitors":{
"Margin1Low":1,
"Competitors":[
{
"Name":"New South Wales",
"Win":"1.60",
},
{
"Name":"Queensland",
"Win":"2.35",
}
],
"HasWinOdds":true,
"TotalOddsColumns":2,
"MarketCount":1,
"PerformVideo":false
},
"EventStatus":"Open",
"IsSuspended":false,
"AllowBets":true
}
}
}
I am using JSON.Net and everything is working fine but in some of my data some element fields are missing for example i am getting Team element inside Competitors as
Teams = from JObject comps in value["Competitors"]["Competitors"]
select (string)comps["Team"]
But in some data Team element is missing and i want to grap Name Element so i am getting Object reference not set to an instance of an object. Error.
This is my code
var query =
from JProperty ev in obj.AsJEnumerable()
from JProperty evid in ev.Value.AsJEnumerable()
let value = (JObject)evid.Value
select new Person
{
EventID = (string)value["EventID"],
Description = (string)value["MainEvent"],
OutcomeDateTime = (string)value["OutcomeDateTime"],
EventStatus = (string)value["EventStatus"],
Teams = from JObject comps in value["Competitors"]["Competitors"]
select (string)comps["Team"]
};
foreach (var b in query)
{
string description = b.Description;
string OutcomeDateTime = b.OutcomeDateTime;
IEnumerable<string> _team = b.Teams;
foreach (var teams in _team)
{
string team = teams.ToString();
}
Console.WriteLine(description);
Console.WriteLine(OutcomeDateTime);
}
How can i get Name element value if Team element does not exist ?
You can deserialize your json to concrete classes
var obj = JsonConvert.DeserializeObject < Dictionary<string, Dictionary<string,RootObject>>>(json);
public class Competitor
{
public string Team { get; set; }
public string Win { get; set; }
}
public class CompetitorsClass
{
public int ActiveCompetitors { get; set; }
public List<Competitor> Competitors { get; set; }
public int TotalCompetitors { get; set; }
public bool HasWinOdds { get; set; }
}
public class RootObject
{
public int EventID { get; set; }
public int ParentEventID { get; set; }
public string MainEvent { get; set; }
public CompetitorsClass Competitors { get; set; }
public string EventStatus { get; set; }
public bool IsSuspended { get; set; }
public bool AllowBets { get; set; }
}
BTW: What is OutcomeDateTime? there is no such field in your json.
The following will work. Use the null-coalescing operator to grab "Name" if "Team" is null. http://msdn.microsoft.com/en-us/library/ms173224.aspx
Teams = from JObject comps in value["Competitors"]["Competitors"]
select (string)comps["Team"] ?? (string)comps["Name"]

Categories