C# Json.NET convert string to JSON key - c#

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();

Related

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.

Pass JSON string form one app to another app (Windows 8.1 Apps) C#

I'm using custom protocol to open another app from windows runtime app. I am using following code snippet:
await Launcher.LaunchUriAsync(new Uri("appb://hello"));
It works fine when there is plain string. But It gives parse error while passing a JSON string.
Invalid URI: The hostname could not be parsed.
I'm creating JSON by:
JObject jObj = new JObject();
jObj.Add("Name", "abcdef");
jObj.Add("Address", "acvdfs");
string json = jObj.ToString();
It gives JSON as:
{ "Name": "abcdef", "Address": "acvdfs" }
Your issue is because you're sending the entire json string to be created as a Uri.
You will need to get the required values out of the string first, and then pass those to your method.
As an example, let's say your
JObject jObj = new JObject();
jObj.Add("Name", "abcdef");
jObj.Add("Address", "acvdfs");
string json = jObj.ToString();
code will give you a "{Name}/{Address}" output - appb://abcdef/acvdfs
Instead of parsing that directly to a string, you will need to get the values out first.
Otherwise your
{ "Name": "abcdef", "Address": "acvdfs" }
is what is causing the
Invalid URI: The hostname could not be parsed.
error.
You could do this in order to retrieve the values from that string:
var values = jObj.Properties().Select(x => x.Value.ToString()).ToArray(); // Gives you an array of the values.
var path = string.Join("/", values); // Creates an "a/b" path by joining the array.
await Launcher.LaunchUriAsync(new Uri("appb://" + path)); // Give that path to create the Uri and pass to your method.
This code assumes you're only using the keys to create the path the way I have. It will work for any number of keys, as it just joins all the values together with "/" - e.g. a/b/c/d/e/f/g etc.
Any questions, just ask :)
Hope this helps!

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);

Find a value of all occurrences from the json string in 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

Parsing a simple Json string

I have gotten a Json string to parse before that was an array of objects much longer than just a simple string, which makes me think that I'm doing something wrong with the formatting.
Here is word for word what our webservice is outputting as the json string:
{"news":"What is Legal/Awesome Dre"}
the first part is simply what I named the string in the application (news) and the second part is the string that will be changing as the song does which is why I would like to pull in a simple string of it.
When I run the app I'm getting a parse error at these lines:
Console.Out.Writeline (content);
news = JsonConvert.DeserializeObject(content);
The application output will show the Json string as it is on the website, but I get an error right after that's telling me Invalid Token: startPath... which last time meant that my Json string was formatted wrong for how I need to grab the data.
Anyone can help me with this?
(P.S. I am working in Xamarin Studio (mono for android) using C#, if that makes any difference)
The problem is that your serialized JSON object isn't a string, it's an object with the string value you want at the "news" property/key/name. This is a simple way to get the string:
dynamic jsonObj = JsonConvert.DeserializeObject(content);
string news = jsonObj.news;
Or you can use an anonymous type:
var jsonObj = JsonConvert.DeserializeAnonymousType(content, new { news = "" });
string news = jsonObj.news;
Or create a type with a string News property:
MyNewsType jsonObj = JsonConvert.DeserializeObject<MyNewsType>(content);
string news = jsonObj.News;
These all work in the following way:
var content = #"{""news"":""What is Legal/Awesome Dre""}";
// above code
Console.WriteLine(news); // prints "What is Legal/Awesome Dre"
Try to put square bracket in your JSON:
[{"news":"What is Legal/Awesome Dre"}]

Categories

Resources