How to find key with array with value in json by Newton - c#

I have a string string json;
Jsons can be
{
...
"...":
{
...
"errors":[{"...":...}]
...
...
}
where ... - can be everything
Example:
"{"common":{"errors":[{"code":"permission_denied","description":"","data":null}]}}"
How can I find existance of errors with unempty array with "code"?

Related

C# Replace an array in a JSON file

I'm trying to replace an array in a JSON file using C# .net 6.0
There is such a JSON file:
{
...
"exchange":{
...
"pair_whitelist": [
"EOS3S/USDT",
"ACH/USDT",
"SOC/USDT"]
...
}
...
}
I want to replace this "pair_whitelist" array with another array
"pair_whitelist": [
"SKM/USDT",
"NEW/USDT",
"XEC/USDT"]
How should I do it?
My attempt was as follows
public static dynamic GetJSONFromFile_dynamic(string path)
{
var data = File.ReadAllText(path);
return JsonSerializer.Deserialize<ExpandoObject>(data);
}
...
var config = GetJSONFromFile_dynamic(path_to_JSON_file);
dynamic a = config.exchange.pair_whitelist;
But I got the following error: Microsoft.CSharp.RuntimeBinder.RuntimeBinderException: ''System.Text.Json.JsonElement' does not contain a definition for 'pair_whitelist''
How to change the value of the pair_whitelist array?
You can try JObject.Parse() to parse Json file and then replace the value of an array
JObject jObject = JObject.Parse(File.ReadAllText(path_to_JSON_file));
if(jObject["exchange"]?["pair_whitelist"] != null) //Check key exists before update
jObject["exchange"]["pair_whitelist"] = ["Stack", "Overflow"];
I would use JsonNode (native to .NET) from System.Text.Json
var json = #"{
""exchange"":{
""pair_whitelist"": [
""EOS3S/USDT"",
""ACH/USDT"",
""SOC/USDT""]
}
}";
var node = JsonNode.Parse(json);
node["exchange"]["pair_whitelist"] = new JsonArray("SKM/USDT", "NEW/USDT", "XEC/USDT");
var newJson = node.ToJsonString();

I can´t find the track and trace number in my json string

I can´t find a value in a json string using json.net
I´ve tried jsonstr[0].track_numbers[0].track_number
This is my json file.
{
"0": {
"increment_id": "112",
"track_numbers": [
{
"track_number": "2223",
"title": "tit",
"carrier_code": "custom"
}
]
},
"live_shipping_status": "Delivered"
}
I want to find the Track_nummber.
dynamic jsonstr = JsonConvert.DeserializeObject(json));
var track = jsonstr[0].track_numbers[0].track_number
(donsent work)
The 0 of your json is a string key, not an index position:
dynamic obj = JsonConvert.DeserializeObject(json);
var trackNumber = obj["0"].track_numbers[0].track_number;
Note the difference in getting the first entry of track_numbers, which is an array.

Get key value pair from JSON string

I have a json string like
{
[
"EnrityList": "Attribute",
"KeyName": "AkeyName",
"Value": "Avalue"
],
[
"EnrityList": "BusinessKey",
"KeyName": "AkeyName",
"Value": "Avalue"
]
}
I have serialized and got an object array.
Could anyone help me to get the key value pair from these object array.
You can use JsonConvert from Newtonsoft.Json to deserialize json into Dictionary.
Dictionary<string, object> values =
JsonConvert.DeserializeObject<Dictionary<string, object>>(jsonstring);
First convert the above string in proper json format by using :
str=str.Replace('[', '{');
str=str.Replace(']', '}');
//replace first occurance of {
int startPos = str.IndexOf('{');
str=str.Substring(0,startPos)+" ["+str.Substring(startPos + 1);
//replace last occurance of }
int endPos = str.LastIndexOf('}');
str=str.Substring(0,endPos)+"]";
This makes the string
str = [{"EnrityList":"Attribute","KeyName":"AkeyName","Value":"Avalue"}, {"EnrityList":"BusinessKey","KeyName":"AkeyName","Value":"Avalue"} ]
Now, since you got the json string, you can easily work with it.
we can use method as given by
How can I deserialize JSON to a simple Dictionary<string,string> in ASP.NET?
foreach(KeyValuePair<string, string> entry in myDictionary)
{
// do something with entry.Value or entry.Key
}
Looking at your example, You are trying to receive a List of certain type of elements,
So First, You will need a class to represent your data type.
class MyType
{
string EnrityList;
string KeyName;
string Value;
}
Then use DesrializeObject method to store it in the variable
var values = JsonConvert.DeserializeObject<List<MyType>>(jsonstring);

Parse Json without any property in c#

In my desktop application i want to parse a json file to Key,Value pair List .
Where Key is unique one and Value contains another list of Key,Value Pair . The striuctre of json string is
{
"mainkey1": {
"subkey10": [
value1
],
" subkey11":[
value2
]
},
"mainkey2": {
"subkey20": [
value0
],
"subkey21": [
value1
]
},
"mainkey3": {
"subkey30": [
value0
],
"subkey31": [
value1
]
}
.
.
.
.
.
}
How can i convert this kind of json string to some .Net object of key,value strings
key=string type value List
Any idea ?
Try deserializing to:
Dictionary<string, Dictionary<string,List<object>>>
...or use something like Newtonsoft's JSON library which has a JObject class representing any sort of JSON object .
Update:
To use the much-easier JavaScriptSerializer, just do this:
var serializer = new JavaScriptSerializer();
var obj = serializer.Deserialize<Dictionary<string, Dictionary<string, List<object>>>>(json);

In C# how can I deserialize this json when one field might be a string or an array of strings?

I have an asp.net-mvc website and i am reading in Json string from a Database. Here is the following json in a DB. It could look like this:
{"description": "Test", "contacts": ["joe#gmail.com", "bill#yahoo.com"], "enabled": true}
or this:
{"description": "Test", "contacts": "joe#gmail.com, bill#yahoo.com", "enabled": true}
so as you can see, the contacts field is either:
a string (with items separated by commas)
an array of strings.
I want to convert to this class:
public class MyJob
{
public string description;
public string[] contacts;
public string enabled;
}
when i try to assign just to a string (changing the above to this: public string contacts;
) using the JavascriptSerializer():
var serializer = new JavaScriptSerializer();
string contacts = serializer.Deserialize<MyJob>(theAboveJsonString).contacts;
I get this error in the cases where its an array: Type 'System.String' is not supported for deserialization of an array.
what is the best way to go about deserializing this to handle the case of:
a string
an array of strings.
for the contact field. I am happy to put any conditional logic needed . .
I tried this:
var contacts = serializer.Deserialize<MyJob>(theAboveJsonString).contacts;
if (contacts is string)
{
jobInfo.contacts = contacts;
}
else
{
jobInfo.contacts = String.Join("; ", contacts );
}
but that didn't seem to fix as i am still getting the error above when its an array
try
var contacts = (new JavaScriptSerializer().DeserializeObject(theAboveJsonString) as Dictionary<string, object>)["contacts"];
if (contacts is object[])
{
jobInfo.contacts = String.Join("; ", contacts as object[]);
}
else
{
jobInfo.contacts = contacts.ToString();
}
For reference see MSDN and here.
You may be interested in some details here: JSON.net - field is either string or List<string>
If you're willing to use Json.NET, have this function:
public string[] getAsArray(JToken token)
{
if (token.HasValues)
{
return token.Select(m => string(m)).ToArray();
}
else
{
return ((string)token).Split(",").Select(s => s.Trim()).ToArray();
}
}
Then usage:
var json = "...";
JObject o = JObject.Parse(json);
string[] contacts = getAsArray(o["contacts"]);
For either JSON the result should be the same.
Try to deserialize contacts into a string array instead of a plain string:
string[] contacts = serializer.Deserialize<MyJob>(theAboveJsonString).contacts;
if the JSON variable is holding a plain string, use:
string[] contacts = serializer.Deserialize<MyJob>(theAboveJsonString).contacts.Split(',');

Categories