Find a value of all occurrences from the json string in c# - c#

I have a JSON object with some data and I want to get all the values of each occurrence of specific key name. Is there any predefined method to search for a key in JSON object for all occurrences or need to write user defined method?
Sample Json
[{"id":"23","name":"sunny","className":"2","class" :{"className":"1","class2" :{"className":"3","class" :{"className":"4"}}}}]

This can be achieved with LINQ to JSON by using the SelectTokens method with a recursive path ..className
class Program
{
static void Main(string[] args)
{
JObject jObject = JObject.Parse(jsonString);
// You would use this because you have an array.
// JArray jObject = JArray.Parse(jsonArray);
// .. - recursive descent
var classNameTokens = jObject.SelectTokens("..className");
var values = classNameTokens.Select(x => (x as JValue).Value);
}
static string jsonString = #"{'id':'23','name':'sunny','className':'2','class' :{'className':'1','class2' :{'className':'3','class' :{'className':'4'}}}}";
static string jsonArray = #"[{'id':'23','name':'sunny','className':'2','class' :{'className':'1','class2' :{'className':'3','class' :{'className':'4'}}}}]";
}
References:
Json.NET - Documentation - Parsing JSON
Json.NET 6.0 Release 1 - JSONPath and F# Support
JSONPath expressions

Related

C# Json.NET convert string to JSON key

My app is accepting user input as json key, how can I convert string a[0].b to json key?
using Newtonsoft.Json.Linq;
string keys = "a[0].b";
dynamic js = dynamic js = JObject.Parse("{'a': [{'b' : 'hello'}, {'b': 'world'}]}");
//Console.WriteLine(js.a[0].b); // world
Console.WriteLine(js["a[0].b"]); // error
Console.WriteLine(js[keys]); // error
I think you will find it challenging to find anything a user might input, but assuming you want "hello" from your example then you should parse to JObject instead of dynamic so that you can use SelectToken or SelectTokens with a string path:
string keys = "a[0].b";
JObject js = JObject.Parse("{'a': [{'b' : 'hello'}, {'b': 'world'}]}");
string hello = js.SelectToken(keys).ToString();

Regular Expressions C#: Clean bad Json string

I get an answer from the server in the form of such JSON:
var zohozoho_atliview92 = {\"Itinerary\":[
{\"Client_Email\":\"garymc\",
\"Client_Name\":\"Gary\",
\"NT_Number\":\"NT-1237\",\"Number_of_Nights\":7,
\"ID\":\"24297940\",
\"Itinerary_Name\":\"Icelandnights\",
\"Tour_Template_Name\":\"Iceland FireDrive\",
\"Departure_Date\":\"2018-07-04\"}
]};
I need to remove this: var zohozoho_atliview92 = {\"Itinerary\":[ and delete last 3 characters ]}; to Deserialize it in my object.
How can i make it using Regular Expressions? Or is there a better variant?
is there a better variant?
Yes you can parse your json escaped string to JObject.
And then you can access any key/value pair from json with Querying JSON with LINQ
Or you can map your JObject to your custom type by using var result = jObject.ToObject<T>();
class Program
{
static void Main(string[] args)
{
var zohozoho_atliview92 = "{\"Itinerary\":[ {\"Client_Email\":\"garymc\", \"Client_Name\":\"Gary\", \"NT_Number\":\"NT-1237\",\"Number_of_Nights\":7, \"ID\":\"24297940\", \"Itinerary_Name\":\"Icelandnights\", \"Tour_Template_Name\":\"Iceland FireDrive\", \"Departure_Date\":\"2018-07-04\"}]}";
JObject jObject = JObject.Parse(zohozoho_atliview92);
Console.WriteLine(jObject);
Console.ReadLine();
}
}
Output:
This is not JSON, it's Javascript (wich object declaration is JSON).
Regular expressions are slow, I would advise you to use Substring
var start=inputString.IndexOf("[");
var end=("]");
var json=inputString.Substring(start, end-start);
There might be some of by one errors, test and correct.
It would be even faster but weaker to hardcode start.

How to Parse the first Property even if the Json is not valid?

I am parsing tons of different jsons which only have the first Property in common.
Depending on the value of this first property I parse the json into different object and also handle possible error differently. However it happens that the json is not valid but I still want to know the value of the first property (as long as this is valid) so I can handle the parsing error. I was wondering if this is possible with Json.Net. Of course I assume that at least the first property is valid, something like this for example:
{
"parsingType":"sometype",
"someothervalue":123,
"someval"123,
}
I tried the following but since the exception is thrown when using .Parse I get no result:
JToken jtoken = JToken.Parse(json);
var theValueIWantToGet = jtoken["parsingType"].Value<string>();
I dont think any parsing engine parses json partially. You will have to parse your json string by yourself if parser fails
string json = "{ \"parsingType\":\"sometype\", \"someothervalue\":12}";
var props = json.Replace('{',' ').Replace('}',' ').Split(',').ToList();
if (props.Count > 0)
{
var firstProp = props[0].Split(':');
var propName = firstProp[0];
var propVal = firstProp[1];
}
You can use a JsonReader (probably JsonTextReader as the concrete type) to parse the JSON as a stream, a bit like XmlReader. So for example:
using System;
using System.IO;
using Newtonsoft.Json;
public class Test
{
static void Main(string[] args)
{
using (var reader = new JsonTextReader(File.OpenText("test.json")))
{
while (reader.Read())
{
Console.WriteLine(reader.TokenType);
Console.WriteLine(reader.Value);
}
}
}
}
On the JSON you've provided, that will give output of:
StartObject
PropertyName
parsingType
String
sometype
PropertyName
someothervalue
Integer
123
Unhandled Exception: Newtonsoft.Json.JsonReaderException [...]
So if you always expect there to be a start object, then a property name, then a string property value, you could easily validate that that's the case and extract the property value.

Data at the root level is invalid - XML parsing

I am very new to programming and not sure where I am going wrong. I have read the other threads with similar error, but I think my problem is even basic.
I get a string generated which contains XML, but it doesnt start with an XML. When I try to parse that string I get the above error.
Is there a way of getting rid of the text and save the text from where the XML starts?
My string:
{"Id":"6a76f781-f592-4320-a116-6ab289505423","Name":"Test - A","AttachmentRequired":false,"FormXml":"
<?xml version=\"1.0\" encoding=\"utf-16\"?>
The easiest way would be to use a JSON parser like Newtonsoft:
public class Data
{
public string Id;
public string Name;
public bool AttachmentRequired;
public string FormXml;
}
var o = JsonConvert.DeserializeObject<Data>(json);
var xml = o.FormXml;
Here is the Nuget package to Newtonsoft which I demonstrated above:
https://www.nuget.org/packages/Newtonsoft.Json/
If you absolutely can't use an external library to transform it into a CLR object, here is how you would do it through string manipulation:
var str = #"{ ""Id"":""6a76f781-f592-4320-a116-6ab289505423"",""Name"":""Test - A"",""AttachmentRequired"":false,""FormXml"":""<?xml version=\""1.0\"" encoding=\""utf-16\""?>""}";
var parts = str.Split(':');
var last = parts[parts.Length -1];
var xml = last.Replace("}","").Replace("\"<","<").Replace(">\"",">");
your string appears to be in json format and xml part of it is a field value for "formxml". screenshot
Easy way is to deserialize the string into object using newtonsoft json, and then parse the value of formxml to your object.
JsonConvert.DeserializeObject<YourClass>(yourstring);

Deserialize JSON array into string array

Say I have a string representing an array of objects in JSON form:
string s = "[{\"name\":\"Person1\"},{\"name\":\"Person2\"}]";
What I want is an array of strings, each string being the string representation of a JSON object - NOT the object itself. It should look something like this:
string[] s = new string[]
{
"{\"name\":\"Person1\"}",
"{\"name\":\"Person2\"}"
};
1) Almost every search I attempt pulls up millions of results on how to simply deserialize a JSON string using (eg) Json.NET. This is not what I want to do.
2) I have tried building a class representing the objects to temporarily loop through a deserialize/serialize mapping each to a string in an array, but the schema for the objects is variable (hence why I only need a string representation).
3) I have attempted a few regex to try and do this, but my JSON string can contain fields that contain JSON strings as their value (icky, but out of my control) and so nested character escaping etc drove me partially mad before I decided to beg for help here.
Surely this should be simple? Anybody got any pointers?
You'll need to deserialize it, and then serialize each object independently.
For example (using Newtonsoft.Json):
string json = "[{\"name\":\"Person1\"},{\"name\":\"Person2\"}]";
var objects = JsonConvert.DeserializeObject<List<object>>(json);
var result = objects.Select(obj => JsonConvert.SerializeObject(obj)).ToArray();
Yields (as a string[]):
{"name":"Person1"}
{"name":"Person2"}
If you try to avoid deserializing and serializing, you're almost certain to run into an edge case that will break your code.
string s = "[{\"name\":\"Person1\"},{\"name\":\"Person2\"}]";
var Json = JsonConvert.DeserializeObject<List<object>>(s);
string[] Jsonn = Json.Select(x => x.ToString()).ToArray();
[] Jsonn returns string array instead of object array with JObject formatted.
Hope this one help you.
Why don't you just use this
string s = "[{\"name\":\"Person1\"},{\"name\":\"Person2\"}]";
string[] t = s.Split(',');
I tried it. It simply gives you string array as you want it....

Categories

Resources