Parsing a simple Json string - c#

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"}]

Related

Line Separator ‘\u2028’ parse incorrect using json.net

static void Main(string[] args)
{
var newLineChar = Char.Parse("\u2028");
var jsonStr = #"{""value"":""some chars " + newLineChar + #"""}";
var jObject = Newtonsoft.Json.Linq.JObject.Parse(jsonStr);
var jsonStrAfterParse = jObject.ToString(Newtonsoft.Json.Formatting.None);
}
I have a JSON string like:
"{\"value\":\"some chars \u2028\"}"
After I try to parse it using Newtonsoft.Json, I got the JSON:
"{\"value\":\"some chars \\u2028\"}"
The Line Separator char '\u2028' was parsed to '\\u2028'. I cannot make sure whether any other chars have the same issue. Can anyone help with this? Thanks.
Pic in immediate window
jsonStr in text visualizer
jsonStrAfterParse in text visualizer
In the comments you established that it's expected behavior, but I thought I'd go into why based on the source code.
Your input string is not valid JSON because of the unescaped control character \u2028, but NewtonSoft.Json is gracefully handling the bad input, and giving correct output of \\u2028 when you ask it to serialize for you.
For the deserialization, it doesn't care that you didn't escape it. It just goes ahead and includes it with your string. No biggie.
But when you ask it to serialize the string for you with .ToString(Newtonsoft.Json.Formatting.None)--which is a Newtonsoft extension method--its job is to give you valid JSON, and by golly, that's what it's going to do, giving you the \\u2028 you see.

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

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....

Console shows correctly-formatted JSON, but JsonObject is unable to parse it

I am connecting to an external API, that (given the parameters), prints a result set in JSON. The objective is to convert this JSON into readable values and add them to an object array. It's a UWP app, so some of the older libraries that I found on the internet were not available any more. The following is the code block that fetches the JSON and then attempts to parse it:
private void beginWork()
{
string feed_data = getFeed().Replace(#"\", "").Trim(new char[1] { '"' });
Debug.WriteLine(feed_data); // <-- THIS PRINTS OUT THE CORRECTLY FORMATTED JSON WITHOUT ANY ESCAPE CHARACTERS
JsonObject obj = JsonObject.Parse(feed_data); // <-- THROWS AN "INVALID JSON ERROR HERE" AND VALUE OF VARIABLE IN AUTOS SHOWS JSON DATA WITH ESCAPE CHARACTERS AND ADDITIONAL QUOTATION MARKS BEFORE AND AFTER THE STRING
}
private string getFeed()
{
HttpClient client = new HttpClient();
string url = "URL HERE";
HttpResponseMessage response = client.GetAsync(url).Result;
return response.Content.ReadAsStringAsync().Result;
}
So what's going wrong here? When the Debug.WriteLine(feed_data); line executed, I see valid JSON in the output console, but still get the parse error.
Edit: Sample JSON (expected and the one that shows in console):
[{"id":"884","author":"795","title":"The sum of ages of 5 children born at the intervals of 3 years each is 50 years. What is the age of the youngest child?","details":" ","datetime":"1439099443","answered":"1","vote":"0","answers":[{"id":"884","author":"788","answer":"4 years","datetime":"1439165670","votes":"0"}]}]
vs the JSON in Autos window and what the parsing fails on:
"[{\"id\":\"884\",\"author\":\"795\",\"title\":\"The sum of ages of 5 children born at the intervals of 3 years each is 50 years. What is the age of the youngest child?\",\"details\":\" \",\"datetime\":\"1439099443\",\"answered\":\"1\",\"vote\":\"0\",\"answers\":[{\"id\":\"884\",\"author\":\"788\",\"answer\":\"4 years\",\"datetime\":\"1439165670\",\"votes\":\"0\"}]}]"
Your JSON string represents JSON array instead of a JSON object. Using JSON.NET (I don't have the dev environment to test in UWP) I got the same error by doing JObject.Parse(feed_data), and it can be fixed by using JArray.Parse(feed_data). So, I strongly suspect that in UWP, the equivalent solution would be using JsonArray.Parse() :
JsonArray arr = JsonArray.Parse(feed_data);

Categories

Resources