JSON via c# , extract array - c#

I have an long JSON that include array.
All the JSON is dynamic and i don't have const structure to this JSON.
Only i know is that "JSON" include this array.
{"employees":[
{"firstName":"John", "lastName":"Doe"},
{"firstName":"Anna", "lastName":"Smith"},
{"firstName":"Peter", "lastName":"Jones"}
]}
I want with c# extract an array of the first name from this .
I tried to do that but not succeed.

use json.net. Deserialize to dynamic.
dynamic x = JsonConvert.DeserialzeObject(jsonStr);

What I normally do is split the JSON string using the C# native String.Split
const string quote = "\""; //You can ignore this line if you like it just adds the "" as a constant string/char value!
string storedValue = "{"firstName":"John", "lastName":"Doe"}" //The JSON value stored either from an HTTPWebRequest or some other method!
string[] str = storedValue.Split(new string[] {quote + "firstName" + quote + ":" }, StringSplitOptions.None); //Split the JSON firstName value!
So the compiler would essentially look for "firstName": and split the firstName value with all the other code, but then if you did str[1] it would also grab lastName value so what I always do after sending the HTTPWebRequest to receive the Request from the target server, and I split the ID I want I then split one final time at the "," to remove last name from the JSON code I want to spit!
string[] finalSplit = str.Split(new string[] { "," }, StringSplitOptions.None);
string output = finalSplit[0].ToString();
as far as I can tell the 'output' string value should equal the "John" value from your JSON code!
If you want to remove the quotes use the Regex.Replace() in C#.
using System.Net.RegularExpressions; //Import C# library using this code at the top of your class or above the Namespace declaration!
Regex.Replace(output, #quotes, ""); //The 'quotes' method was declared at the top of the first code block it was that code I said you could ignore if you really wanted to!
after removing the quotes the last thing to do is just place output into a label, textbox, or maybe even a file using System.IO.streamWriter!
Also btw how where you getting the JSON code from a file or VIA an HTTPWebRequest? If you are getting the JSON code from an HTTPWebRequest I recommend converting the code to UTF-8 just to be on the safe side!
Now I know there is a more official way to read JSON in C# but this is MY method and it works for me so I see no reason in using an official method if I have one that works just as well, but again this is just my opinion! :)

Related

JSON Data format to remove escaped characters

Having some trouble with parsing some JSON data, and removing the escaped characters so that I can then assign the values to a List. I've read lots of pages on SO about this very thing, and where people are having success, I am just now. I was wondering if anyone could run their eyes over my method to see what I am doing wrong?
The API I have fetching the JSON data from is from IPStack. It allows me to capture location based data from website visitors.
Here is how I am building up the API path. The two querystrings i've added to the URI are the access key that APIStack give you to use, as well as fields=main which gives you the main location based data (they have a few other blocks of data you can also get).
string api_URI = "http://api.ipstack.com/";
string api_IP = "100.121.126.33";
string api_KEY = "8378273uy12938";
string api_PATH = string.Format("{0}{1}?access_key={2}&fields=main", api_URI, api_IP, api_KEY);
The rest of the code in my method to pull the JSON data in is as follows.
System.Net.WebClient wc = new System.Net.WebClient();
Uri myUri = new Uri(api_PATH, UriKind.Absolute);
var jsonResponse = wc.DownloadString(myUri);
dynamic Data = Json.Decode(jsonResponse);
This gives me a JSON string that looks like this. (I have entered on each key/value to show you the format better). The IP and KEY I have obfuscated from my own details, but it won't matter in this summary anyway.
"{
\"ip\":\"100.121.126.33\",
\"type\":\"ipv4\",
\"continent_code\":\"OC\",
\"continent_name\":\"Oceania\",
\"country_code\":\"AU\",
\"country_name\":\"Australia\"
}"
This is where I believe the issue lies, in that I cannot remove the escaped characters. I have tried to use Regex.Escape(jsonResponse.ToString()); and whilst this does not throw any errors, it actually doesn't remove the \ characters either. It leaves me with the exact same string that went into it.
The rest of my method is to create a List which has one public string (country_name) just for limiting the scope during the test.
List<IPLookup> List = new List<IPLookup>();
foreach (var x in Data)
{
List.Add(new IPLookup()
{
country_name = x.country_name
});
}
The actual error in Visual Studio is thrown when it tries to add country_name to the List, as it complains that it does not contain country_name, and i'm presuming because it still has it's backslash attached to it?
Any help or pointers on where I can look to fix this one up?
Resolved just from the questions posed by Jon and Luke which got me looking at the problem from another angle.
Rather than finish my method in a foreach statement and trying to assign via x.something,,, I simple replaced that block of code with the following.
List<IPLookup> List = new List<IPLookup>();
List.Add(new IPLookup()
{
country_name = Data.country_name,
});
I can now access the key/value pairs from this JSON data without having to try remove the escaped characters that my debugger was showing me to have...

C# Pass filename as json parameter- Getting error "Unrecognized escape sequence. "

I want to pass a filepath through JSON. On deserializing I am getting error:
Unrecognized escape sequence. (43): {"Jobtype": "StepBatch","SelectedId": "D:\Input\file1.CATPart"}
I have escaped characters but it still shows error...am I missing something here?
string json = "{\"Jobtype\": \"StepBatch\",\"SelectedId\": \"D:\\Input\\file1.CATPart\"}";
var jsonObj = new JavaScriptSerializer().Deserialize<List<Arguments>>(json);
The problem is that the content of your string at execution time is:
{"Jobtype": "StepBatch","SelectedId": "D:\Input\file1.CATPart"}
That's not valid JSON, because of the backslashes in the value for SelectedId. You'd need the JSON to be:
{"Jobtype": "StepBatch","SelectedId": "D:\\Input\\file1.CATPart"}
so your C# would have to be:
string json = "{\"Jobtype\": \"StepBatch\",\"SelectedId\": \"D:\\\\Input\\\\file1.CATPart\"}";
However, given that you're immediately deserializing the JSON anyway, I'd suggest getting rid of the JSON part entirely, and just creating the Arguments values yourself.
If you need to produce JSON, create the right values directly, and then get JavaScriptSerializer (or preferrably Json.NET) to create the JSON for you, instead of hand-coding it.

In C#, How can I deserialize this result I am getting from a REST service?

I am getting this string result back from a rest service:
Test: [[]] MessageDetail: [['{"Field1": "Value1", "Field2": "Value2", "BM Fields": "{\'BM Field 1\': \'BM Value 1\', \'Field2\': \'\'}", "Field 2": "Value 4"}']]
and unfortunately only the data inside the "MessageDetail" tag is valid json (which i will send to a json deserializer) so i trying to figure out the best way to remove the unnecessary part of the message. So i want to parse out the string inside the message which I can
{"Field1": "Value1", "Field2": "Value2", "BM Fields": "{\'BM Field 1\': \'BM Value 1\', \'Field2\': \'\'}", "Field 2": "Value 4"}
what is the best way to strip out the first part of the string before the first apostrophe as well as the last part of the string after the last apostrophe so I can just get what is listed in the second section above?
You can obtain this by using both Substring and IndexOf, considering you want to use the "{" as a reference
string output = input.Substring(input.IndexOf("{")+1,input.Length-2)
This code only intends to omit the "{" and "}"
After this just use your JSON parser on output
Step 1: using string remove function
string output = input.Remove(startIndexOfApostrophe, count);
Step 2:
In Visual Studio, paste special as Json to generate the classes
Step 3:
Deserializing json
I cannot write exact code, but can give you right algo since am typing from mobile:
Var array = result.split('[[');
Var json = array.last();
json = json.replace(']]', '');
Send this 'json' variable for deserialization.

unexpected non-whitespace character after JSON data

string result="12334,23432,3453455";
I am getting this string through Ajax call but it gives me the following error:
"unexpected non-whitespace character after JSON data"
When I remove comma's between strings it works fine .How to handle this?. I want to put value in textarea with comma's after the Ajax call
Whatever's outputting that isn't doing so in JSON format, but more like CSV.
A few options:
If you're able, fix the output method to correctly output JSON
Parse the string like a CSV
e.g. "12334,23432,3453455".split(',')
Conform the output to JSON first, then parse
e.g. JSON.parse("["+"12334,23432,3453455"+"]") (wrap with [])
Specify dataType:'text' in your $.ajax call.
Options 1-3 of the above would result in [12334,23432,3453455] as a javascript array of numbers, while Option 4 will simply result in "12334,23432,3453455" as a string.
BTW, using JSON.NET, this is what it should result in:
// As an array:
Int32[] ary = new[]{ 12334, 23432, 3453455 };
Console.WriteLine(JsonConvert.SerializeObject(ary));
// [12334,23432,3453455]
// As a string:
String str = "12334,23432,3453455";
Console.WriteLine(JsonConvert.SerializeObject(str));
// "12334,23432,3453455"
Your data has to be parsed by your JSON parser.
If your data is an array, your string should look like:
"[12334,23432,3453455]"
or should it be astring:
"\"12334,23432,3453455\""

How can I manage ' in a JSONP response?

I need to manage char like ' in my JSONP request, trought Ajax by jquery. So (from C#) this is what I've done :
myText = "Hello I'm a string";
myText.Replace("'", "\'");
Response.Write(Request["callback"] + "({ htmlModulo: '" + myText + "'});");
but on Client side it broke :
parsererror - SyntaxError: missing } after property list
so, How can I manage ' if the replace doesnt works?
Serializing JSON is already solved for you by .NET. Use System.Web.Script.Serialization.JavaScriptSerializer:
var serializer = new JavaScriptSerializer();
To construct JSONP you just need to concatenate prefix (either hardcoded or passed in "callback" query parameter) and suffix (normally just ), but sometimes you may need to pass extra parameters depending on what caller expect like ,42, null) ) with JSON text.
Sample below shows constructing JSONP based on "callback" parameter, replace value of jsonpPrefix based on your needs.
var myText = "Hello I'm a string";
var jsonpPrefix = Request["callback"] + "(";
var jsonpSuffix = ")";
var jsonp =
jsonpPrefix +
serializer.Serialize(new {htmlModulo = myText}) +
jsonpSuffix);
Response.Write(jsonp);
You should always use a serializer, because doing it yourself means you're more likely to mess up and violate the JSON spec. For example, you are not quoting the key, which is required by JSON, so jQuery and other JSON parsers will be very confused. It will handle all characters that need to be escaped, as well.
More on constructing JSON can be found in How to create JSON string in C#.
leave the text as it is, but use double quotes to escape it in json:
Response.Write(Request["callback"] + "({ htmlModulo: \"" + myText + "\"});");
you could also try this one:
var jsonSerializer = new System.Web.Script.Serialization.JavaScriptSerializer();
string json = jsonSerializer.Serialize(yourCustomObject);
and then i leave this as well
You would need to do:
myText.Replace("'", "\\'");
If you want an escaped single quote in the value of your htmlModulo property. However, your actual JSON would still be invalid. According to the specification, you should be using double quotes to surround key names and values. Thus, for your response to be valid, you would need to send:
{"htmlModulo": "myText value"}
It really shouldn't matter with JSONP since that relies on inserting a new script element into the DOM. Thus even the improper JSON would be interpreted correctly by the JavaScript interpreter. The problem is if you ever request the data as plain JSON. If you do that, then the way you are sending it now will fail with a variety of libraries. In particular, jQuery will fail silently with improper JSON.

Categories