JSON.Net, customizing serialization of List<T> - c#

I'm serializing a List<T>, which I suppose is an array of objects when you think about it. When serializing the populated List<T>, I get a result similar to the following:
[
{
"foo": "a1",
"bar": "b1"
},
{
"foo": "a2",
"bar": "b2"
},
{
"foo": "a3",
"bar": "b3"
}
]
This is of course a json array of objects as you'd expect. However, I have a different need. I require the serialization of the List<T> to be separate objects as shown.
{
"foo": "a1",
"bar": "b1"
}
{
"foo": "a2",
"bar": "b2"
}
{
"foo": "a3",
"bar": "b3"
}
I'm planning to use RegEx to update the json string, but before I went through that step, I wanted to find out if there is an in-the-box solution in json.net to deal with specific formatting needs. Granted, I have not read every line of documentation but, I've read a good bit of it and nothing stood out.
Thanks.

My approach was wrong here. The real issue is at the target for where the json will be ingested. Rather than trick json.net into serializing invalid json, I am going to refocus my energy on why the target system is interpreting my json file incorrectly.

Why dont try to use NEWTONSOFT it will make all the work for you just have to implement the library and return the Json ready to use
public static string ToJson(object obj)
{
//Remember to JSON.parse() in aspx so you can work with data returned
return Newtonsoft.Json.JsonConvert.SerializeObject(obj);
}
Hope this help you

Related

Passing IEnumerable as parameter

I have a problem understanding how IEnumerable works in C#.
Background
I'm developing an Azure Function, the purpose of which is to combine data from different API's. I have used an API generator for each of the sources.
Currently I'm trying to make a Post request with one of the generated functions, but
I'm having trouble providing data in the correct format for the parameter.
First of all, in the API's Swagger documentation, it says that the function I'm using requires a Request body that looks like this:
[
{
"name": "string",
"address": "string"
"properties": {
"prop1": "string",
"prop2": "string",
},
}
]
... and when looking at the function in Visual Studio, function needs parameter type of " IEnumerable<> body ".
What have I tried?
First I thought that I could just create an object and pass it as a parameter. Something like this:
var newProperties = new ApiProperties()
{
Prop1 = "example",
Prop2 = "example"
};
var newApiData = new ApiData()
{
Name = "example",
Address = "example",
Properties = newProperties,
};
... and passing newApiData as an parameter to the function.
await api.PostDataAsync(newApiData)
But this does not work because parameter needs to be IEnumerable.
Problem
How can I pass the request body information as an IEnumerable type parameter?
var enumerable = new ApiData[] { newApiData };
That is, you need to pass an IEnumerable (array, list), not a single entry
Instead of directly sending the data, just put the data in an array before sending:
await api.PostDataAsync(new ApiData[] { newApiData });
Instead of an array, create a list:
await api.PostDataAsync(new List<ApiData>() { newApiData });
The IList interface inherits from an IEnumerable, that's why a list will work.
I believe it will be very interesting for you to study the following answer: https://stackoverflow.com/a/4455507/3231884

C# Merge two json and remove missing property

i am working with two unknown json (i don't know structure) and i need to merge these two, i also have to remove missing properties, I know I probably haven't explained myself very well, so I'll give you an example.
Json 1:
{
'FullName': 'Dan Deleted',
'Deleted': true,
'DeletedDate': '2013-01-20T00:00:00',
'location': {
'nation': 'it',
'city': 'Madrid'
}
}
Json 2:
{
'FullName': 'Dan',
'Age': '23',
'DeletedDate': '2014-01-20T00:00:00',
'location': {
'nation': 'es'
}
what I would:
{
'FullName': 'Dan',
'Deleted': true,
'DeletedDate': '2014-01-20T00:00:00',
'location': {
'nation': 'es',
'city': 'Madrid'
}
}
I'm using Newtonsoft.Json and i've saw that there is a method merge json1.merge(json2) but in this way i will get something like that:
{
"FullName": "Dan",
"Deleted": true,
"DeletedDate": "2014-01-20T00:00:00",
"location": {
"nation": "es",
"city": "Madrid"
},
"Age": "23"
}
I hope you understand.
In practice I would like that if the property is present in both json, in the result the value is that of json2, but if a property is present only in json2, in the result this should not be there. While if it is only in json1 then it will be in the result.
How could I do?
Thank you very much!😃😃
According to Newtonsoft's example its a matter of which JObject it is invoked on and which other JObject is passed in as an argument. The one passed in by argument is the one that overwrites. Given these parameters, you will want to get the API responses as a string and then deserialize with JObject.Parse(string)
Also note that prior to the merge you can probably run some validation logic on these parsed objects to suit your needs
You should probably also explore the JsonMergeSettings object that is shown in the example, as it may include some finer grained options that you may want for your merge

NewtonSoft JsonPath with C# Syntax

I have a set of objects which I'm deserializing using NewtonSoft.Json 13.0.1. My project is using .Net 5.0 and the language is C#. I want to use JsonPath (Json Path) syntax to determine whether an object matches a given criterion, in particular, whether parent.child.property1 matches the string 'appname.' It seems that the only way I can use a filter expression is if I have an array. e.g., in the following, I have been unable to come up with a JsonPath expression which works. An example Json is as follows:
{
"parent": {
"child": {
"property1": "appname",
"property2": "57fc697c44",
"property3": "yes"
}
}}
As a workaround, what I've done is wrap the previous Json in an array, and then used a filter expression, so, with the following Json:
{
"item": [
{
"parent": {
"child": {
"property1": "appname",
"property2": "57fc697c44",
"property3": "yes"
}
}
}
]}
and this JsonPath expression:
$..[?(#.parent.child.property1=='appname')]
I get a match.
As an aside, I originally tried (notice the single dot)
$.[?(#.parent.child.property1=='appname')]
which didn't work. I don't understand why because my understanding is that '$.' refers to the root of the Json. If anyone can help me to understand this as well, I'd appreciate it.
Thank you.

How to check In C# JArray have specific key pair

I am working on JArray in .NET CORE and I am getting random structure of this one specific key, hence getting different error. I need to know if JArray has specific child Array and if Child JArray have specific key pair (NOT VALUE) i.e. value{ "Id":""} one of error is following;
Accessed JArray values with invalid key value: "id". Int32 array index expected.
at Newtonsoft.Json.Linq.JArray.get_Item(Object key) at
the standard structure I am expecting is as following;
{[value, [
{
"id": "7ef82869-e235-69a2-f81e-3a9664e89bc4",
"value": ""
}
]]}
sometime I get as, meaning throw null error where I am trying to map Id.
{[value, [
{
"value": ""
}
]]}
and some Time I don't get this property at all
I am trying following check to cover all scenario but Its not really working.
code
if (answerItems.value != null && answerItems.value.HasValues && answerItems.value["id"]!=null)
{
I received some constructive criticism on the brevity of my answer so I figured I would elaborate to help you through your issue.
First, let's take a look at your JSON. In short, it isn't valid. In fact, it isn't even close to valid JSON. I can only assume you meant something like this:
{
"values" : [{ "id" : "7ef82869-e235-69a2-f81e-3a9664e89bc4", "value": "" }]
}
I would suggest that anytime you are trying to parse data like this and you run into issues you start trouble shooting by validating the data itself. I like to use JSONLint for this.
Next, it is difficult from your example code to tell exactly what you are trying to do. I can only guess that you are attempting to use the dynamic object method of parsing and working with the data. A downside to this method is it is difficult to validate your data before you work with it.
Instead, I would use the Newtonsoft.Json.Linq.JObject.Parse method. This gives you some tools for working with and validating the information. Below I have included a very simple example of how this would be done.
using System;
using Newtonsoft.Json.Linq;
public class Program
{
public static void Main()
{
string json = "{ \"values\": [{ \"id\": \"7ef82869-e235-69a2-f81e-3a9664e89bc4\", \"value\": \"\" }] }";
JObject obj = JObject.Parse(json);
// Check to see if we got our value array
if (obj.ContainsKey("values")) {
JArray values = (JArray)obj["values"];
// Do we have any values in our array?
if (values.Count > 0) {
JObject firstItem = (JObject)values[0];
// We check to see if we have an ID parameter
if (firstItem.ContainsKey("id")) {
Console.WriteLine(firstItem["id"]);
}
}
}
}
}
As I mentioned in my original post, I would strongly recommend reviewing the Newtonsoft.Json documentation.

Deserialize complex JSON data in C#

I'm just an amateur in C# programming. Now i have a JSON data that looks like following
{
type: "xxx",
width: "xxx",
dataSource: {
"chart": {
"caption": "xxx"
},
"data": [
{},
{}
]
}
}
I'm having the whole data as escaped string. now after Unescape when I'm using JavaScriptSerializer as follows
var data = ser.Deserialize<Dictionary<String, Object>>(chartData);
I'm able to get the "type", "width" as
data["width"]
data["type"]
Now I have to get the value of "caption". Any suggestion how to get that, I believe the dictionary structure need to be changed but I'm stacked for my lack of knowledge in C#
If you know the object's scheme you man want to create a class that represents in and then deserialize the json into it:
YourKnownClass obj = JsonConvert.DeserializeObject<YourKnownClass>(json);
Console.WriteLine(obj.dataSource.chart.caption.Value);
Another option is by using a dynamic type (There is no good reason using a dynamic object if you know the schema and can create a matching C# class. This has a performance impact as well):
dynamic obj = JsonConvert.DeserializeObject<dynamic>(json);
Console.WriteLine(obj.dataSource.chart.caption.Value);
BTW, In this example i'm using json.net which is a popular library.

Categories