Getting an array of objects fron JSON string with Json.net - c#

I am using Json.net for a project I do in C#, and I got lost looking for how to parse my JSON string to Objects.
so in my program I have a class Person that has 3 properties -
string Name,
int ID,
List condition
every time the user adds a person, the program writes it to a file, it looks like this:
{
"Name": "fsdf",
"ID": 234234,
"Conditions": [
"2",
"4",
"6"
]
}
{
"Name": "David",
"ID": 5555555,
"Conditions": [
"2",
"4",
"6"
]
}
The function I use to add new objects to the file-
public void AddPerson(Person person)
{
string output = JsonConvert.SerializeObject(person, Formatting.Indented);
StreamWriter file = new StreamWriter(#"../Data/Persons.json",true);
file.WriteLine(output);
file.Close();
}
Now I have a ComboBox and I want to fill it with all the names from the JSON string. and also there is a TextBox where the user inputs the ID number, and I want it to auto complete the input with the IDs that are already existing in the JSON file.
I think a good way is to parse each JSON object in my file to a Person object (in Persons array), then using a foreach loop add all the IDs in to a list which I can access later, and add all the names to the ComboBox.
using Newtonsofts' Json.net -
how do I parse each object in the JSON string to a separate Person object in my program?
*I've been looking through the docs and I cant find a solution.. also tried google but found nothing that addresses my problem.
*I started coding again after a long time off, and I am a bit new to JSON so I am sorry if my question is super noob :D.

Related

Deserializing json without key name

i have json answer, like this, without key names, only values
[
[
1645724820000,
"35893.01000000",
"35898.38000000",
"35850.01000000",
"35876.07000000",
"10.19782000",
1645724879999,
"365831.59479120",
335,
"2.90744000",
"104298.60366850",
"0"
],
[
1645724880000,
"35876.79000000",
"35910.93000000",
"35864.93000000",
"35910.93000000",
"8.15710000",
1645724939999,
"292722.41648950",
326,
"3.18438000",
"114275.09871200",
"0"
]
]
i try deserializing with Newtonsoft, next C# code
public class Root
{
public List<List<String>> MyArray { get; set; }
}
//Root Pair = JsonConvert.DeserializeObject<Root>(Data2Json);
but it does't work, i'm begginer programmer, help pls, how i can deserializing it json. I guess it needs to be deserialized into some kind of array or list of values since there are no key names, but I don't know how, Google doesn't help anymore
you can try this code
List<List<string>> list = JsonConvert.DeserializeObject<List<List<string>>>(json);

Deserializing Json with unexpected characters in property

My application processes a Json that contains a list of objects. The properties of these objects are not completely known to me.
Example, in the following Json, only property "Id" is known to my application:
{"msgs": [
{
"Id": "Id1",
"A": "AAA"
},
{
"Id": "Id2",
"B": "BBB"
},
{
"Id": "Id3",
"C": "CCC"
}
]}
I want to parse these messages and extract the Id of each message. This has been working fine with the following code:
public class RootElem
{
[BsonElement("msgs")]
public List<JToken> Records { get; set; }
}
then read
var rootElem = JsonConvert.DeserializeObject<RootElem>(JSON_DATA);
Once I have my rootElem, I can iterate over each record in "Records" and extract the Id.
The problem is that sometime, some of the records will contain unexpected characters.
Example:
{
"Id": "Id2",
"B": "THIS CONTAINS UNEXPECTED DOUBLE QUOTE " WHAT SHOULD I DO?"
}
I tried adding error handling settings, but that didn't work:
var rootElem = JsonConvert.DeserializeObject<RootElem>(data, new JsonSerializerSettings
{
Error = HandleDeserializationError
});
private static void HandleDeserializationError(object sender, ErrorEventArgs errorArgs)
{
var currentError = errorArgs.ErrorContext.Error.Message;
Console.WriteLine(currentError);
errorArgs.ErrorContext.Handled = true;
}
I want to be able to access the rest of the records in the list, even if one/some of them contain these invalid chars. So I'm ok if "B" value of the 2nd record is return as null, or if the 2nd record is null altogether.
How can I achieve this?
p.s. I'm using Newtonsoft Json but I'm open to using other libraries.
The issue here is that what your application is receiving is not valid JSON, hence the errors you are seeing. The input should be properly escaped prior to being submitted to this method. If this is behind an HTTP API, the appropriate response would be a 400 as the request is not in a valid format. If you really need to work around this it's possible you could implement your own JsonConverter class and decorate the converting class with it, but this may not be possible as the JSON itself is invalid and the JsonReader is going to choke when it hits it.

How do I parse the below dynamic JSON

I have a json which is badly formatted. I want to take out the status and order id from that json. Tried JSON parsing with object, but did not get the result. Please help,
My Json,
{
"formname": [
"Sale_Order_API",
{
"operation": [
"add",
{
"values": {
"Order_ID": "1250",
"Email": "xyz#yws.in",
"Order_Value": "100",
"Restaurant_Name": "HiTech",
"Order_Date": "13-Aug-2019",
},
"status": "Failure, Duplicate values found for
'Order ID'"
}
]
}
]
}
Please help.
This is my first question , please ignore mistakes.
I have tried something like this, But not able to get the inner values
dynamic resultdata = json_serializer.DeserializeObject(postData);
If I understand you correctly, you want to deserialize this JSON. On 'http://json2csharp.com/#' you can generate a C # class from your JSON. Or right by your own. There are plenty of tutorials on the Internet. In case your class, where you give the values of the Json, is called 'JSONResult', you could access the values as follows
var resultdata = JsonConvert.DeserializeObject<JSONResult>(postData);
JSONResult outPut = resultdata;
Console.WriteLine(outPut.formname[0]);
But the longer I look at the format of your JSON, the more confused I get. Where did you get the JSON from? From an API?

Razor Umbraco 7 CurrentPage.GetPropertyValue Serialize issue

i am using an for each but its not iterating properly instead its displaying a characters i think its Conversion issue can any one help me on this.
the array returing is CurrentPage.GetPropertyValue("promo")
[ { "alias": "1", "content": "1", "img": "/media/1069/509253678.jpg" }, { "alias": "Slide 2", "content": "2", "img": "/media/1074/636609180.jpg" } ]
the code is
#{
if (CurrentPage.HasValue("promo"))
{
var promoListValue = CurrentPage.GetPropertyValue("promo");
foreach (var item in promoListValue)
{
<span>#item </span>
}
}
}
but its displaying like this
You should implement a Property Value Converter for your custom datatype (now you are just getting the string out!)
so that from the json you saved in the node you can get the actual type.
See https://our.umbraco.org/documentation/extending/property-editors/value-converters
The issue you're seeing is because you are using the dynamic objects, which struggle to convert objects sometimes. It thinks the promo value field is a string, so your for-each loop is basically looping through each character of the string.
As Eyescream mentioned, you could write a property value converter to make your life much easier.
If the object is JSON, just derserialise it to a type and iterate over it.
http://www.newtonsoft.com/json/help/html/Overload_Newtonsoft_Json_JsonConvert_DeserializeObject.htm

c# dynamic json objects with dynamic names question

Before I get flagged for duplicate, I have the code from Dynamic json object with numerical keys working quite well now. The question with my numeric keys is that unfortunately, the JSON string I am getting is initially delimited by year, so would I use reflection to attempt to create a dynamic property on a dynamic object, and if so how? I know with a dynamic object I can't have obj["2010"] or obj[0]. In JavaScript this is no problem, just trying to get it working in C#. Ideas?
Example of JSON being returned:
{
"2010": [
{
"type": "vacation",
"alloc": "90.00"
},
Alternatively, sometimes the year is the second element as such:
I have no control over this json.
{
"year": [],
"2010": [
{
"type": "vacation",
"alloc": "0.00"
},
Maybe I'm misunderstanding your question, but here's how I'd do it:
static void Main(string[] args) {
var json = #"
{
'2010': [
{
'type': 'vacation',
'alloc': '90.00'
},
{
'type': 'something',
'alloc': '80.00'
}
]}";
var jss = new JavaScriptSerializer();
var obj = jss.Deserialize<dynamic>(json);
Console.WriteLine(obj["2010"][0]["type"]);
Console.Read();
}
Does this help?
I wrote a blog post on serializing/deserializing JSON with .NET: Quick JSON Serialization/Deserialization in C#
I have up-voted the question and JP's answer and am glad I dug around the internet to find this.
I have included a separate answer to simplify my use case for others to benefit from. The crux of it is:
dynamic myObj = JObject.Parse("<....json....>");
// The following sets give the same result
// Names (off the root)
string countryName = myObj.CountryName;
// Gives the same as
string countryName = myObj["CountryName"];
// Nested (Country capital cities off the root)
string capitalName = myObj.Capital.Name;
// Gives the same as
string capitalName = myObj["Capital"]["Name"];
// Gives the same as
string capitalName = myObj.Capital["Name"];
Now it all seems quite obvious but I just did not think of it.
Thanks again.

Categories