Parsing through MSDN text? - c#

Trying to figure out how I can parse through this information, it looks like JSON but I can't tell if it is or not (no .json at the end). I've been treating it as JSON and have been trying to parse through it
string url = "https://services.social.microsoft.com/searchapi/en-US/Msdn?query=" + query + "&maxnumberedpages=5&encoderesults=1&highlightqueryterms=1";
HtmlDocument doc = new HtmlDocument();
HttpWebRequest request = (HttpWebRequest) WebRequest.Create(url);
var response = (HttpWebResponse) request.GetResponse();
var reader = new StreamReader(response.GetResponseStream());
var objText = reader.ReadToEnd();
List<string[]> data = JsonConvert.DeserializeObject<List<string[]>>(objText);
foreach (string[] test in data)
{
foreach (string sub_text in test)
{
Console.WriteLine(sub_text);
}
}
But it gives me an error that it's not a JSON array, so I'm beginning to think it's not JSON.
I'm just looking for a push in the right direction, here's a sample of the data I would get:
https://services.social.microsoft.com/searchapi/en-US/Msdn?query=dynamic%20arrays&maxnumberedpages=5&encoderesults=1&highlightqueryterms=1
and I would want to grab the all arrays that the have 'id' at the start. How can I go about this?

It is valid Json.
Problem is that you are trying to Deserialize into Array which is not correct.
var data = JsonConvert.DeserializeObject(objText);

Looks like the issue is this line
List<string[]> data = JsonConvert.DeserializeObject<List<string[]>>(objText);
What you are trying to deserialize is not a string array, it's an object. To correctly deserialize it, you would need to create a set of classes that model the data structure. You may also explore using a Jobject in the JSON.net library as an alternative.

Related

How to deserialize dynamic Json objects?

I am currently receiving the following JSON response from my api:
{"Lastname":["ERRLASTNAMEEMPTY"],"Firstname":["ERRFIRSTNAMEEMPTY"]}
Note that the above response is dynamic - i.e sometimes I can have FirstName, sometimes LastName, sometimes both. This response is based on the validation of data.
My question is - is there a way to deserialize this response using JsonSerializer.DeSerialize?
I have tried to use it like this but it does not work:
var errorBody = JsonSerializer.Deserialize<dynamic>(body, serializerOptions);
JsonSerializer.Deserialize<Dictionary<string,string[]>>(body, serializerOptions);
You can work with dynamic JSON objects with JObject like that:
var data = JObject.Parse(body);
And later you are able to access values with data["Lastname"]?.Value<string>(); and such, the way you want.
JsonSerializer.Deserialize<ExpandoObject>(body, serializerOptions);
// introduce a dynamic object from a string :
// {"UrlCheckId":581,"Request":{"JobId":"a531775f-be19-4c78-9717-94aa051f6b23","AuditId":"b05016f5-51c9-48ba-abcc-ec16251439e5","AlertDefinitionId":108,"JobCreated":"2022-05-20T07:09:56.236656+01:00","UrlJobId":0,"BatchJobId":"e46b9454-2f90-407d-9243-c0647cf6502d"},"JobCreated":"2022-05-20T07:10:21.4097268+01:00"}
// ...The UrlCheckId is an int primitive and Request is our UrlCheckJobRequest object.
dynamic msg = JsonConvert.DeserializeObject(message);
// to access an int (primitive) property:
int id = msg.UrlCheckId;
// to access an object, you might have to serialize the request into a string first...
var r = JsonConvert.SerializeObject(msg.Request);
// ... and then deserialize into an object
UrlCheckJobRequest request = JsonConvert.DeserializeObject<UrlCheckJobRequest>(r);

Detect end of json object using Newtonsoft.Json

I have a string that starts with a JSON object but after the end of which the string goes on (something like {"a":"fdfsd","b":5}ghresd). The text afterward can contain any character and the JSON can be anything allowed for a JSON.
I would like to deserialize the JSON object and know where it ends because I want to process the rest of the string afterward, how do I do that, preferably using Newtonsoft.Json?
You could make use of the SupportMultipleContent property, for example:
var json = "{\"a\":\"fdfsd\",\"b\":5}ghresd";
var reader = new JsonTextReader(new StringReader(json));
reader.SupportMultipleContent = true;
//Read the first JSON fragment
reader.Read();
var serializer = new JsonSerializer();
var result = serializer.Deserialize(reader);
//Or if you have a class to deserialise into:
//var result = serializer.Deserialize<YourClassHere>(reader);
//Line position is where the reader got up to in the JSON string
var extraData = json.Substring(reader.LinePosition);
This piece of code might not work as expected if your json has multiple lines:
var extraData = json.Substring(reader.LinePosition);
You might need to consider adding additional check:
if(reader.LineNumber != 1)
throw new NotSupportedException("Multiline JSON objects are not supported.");
Or you can take that value from private field using Reflection:
var charPosition = (int)reader.GetType().GetField("_charPos", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(reader);
JsonTextReader source code

pulling a python list out of a json object and converting it to something usable in C#

I have a python server that sends a list of strings as a json object to a C# client. On the client end I have this code to deserialize the object:
try
{
var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
var jsonObject = serializer.DeserializeObject(sr.ReadToEnd());
textBox4.Text = jsonObject.ToString();
}
catch (Exception e){
textBox2.Text = e.ToString();
}
What i'm getting as a result is: "System.Object[]"
Ideally I would like to put the contents of the list into an array.
can anyone point me in the right direction?
You are getting an array of generic objects, however I supose that you don't want this and you prefer getting a more usable result, so:
Create a class with the object's properties (for example: id, name, etc.). You can use this page in order to autogenerate the class.
Then deserialize the input into objects of the class that you have created in the first step, with the following code:
MyNewClass myNewClassList = serializer.Deserialize<MyNewClass>(sr.ReadToEnd());
I hope this can help you
Edit
This is a complete example created with the new information that you tell me in the comments:
var json = "[\"file0\",\"file1\",\"file2\",\"file3\",\"file4\",\"file5\"]";
var serializer = new JavaScriptSerializer();
var files = serializer.Deserialize<List<String>>(json);

Parse Dynamic JSON string

I am getting a JSON response from a server but the JSON is not in a one format. So obviously there is no point of creating classes to deserialize it. So, I tried to use dynamic but I am unable to read the response.
The sample JSON String is
" {"hm_xytrict":"HM Tricky District - oop","hmSD":"HM Pool District"}"
Note that "hm_xytrict" and "hmSD" will be different every time
I am using
dynamic jsonResponse = JsonConvert.DeserializeObject(responseString);
For this specific case I can use jsonResponse.hm_xytrict and jsonResponse.hmSD but since they are also dynamic so how can I read jsonResponse for all cases.
Thank you,
Hamza
So you can use a different part of the JSON.NET api to parse and extract data from your object:
var jObj = JObject.Parse(json);
foreach (JProperty element in jObj.Children())
{
string propName = element.Name;
var propVal = (string)element.Value;
}
Even more interesting, you can directly parse a JSON string to a dynamic object
string responseString = #"{""hm_xytrict"":""HM Tricky District - oop"",""hmSD"":""HM Pool District""}";
dynamic jsonResponse = JObject.Parse(responseString);
foreach (var item in jsonResponse)
{
Console.WriteLine(item.Name);
Console.WriteLine(item.Value);
}
Which in your example will output
hm_xytrict
HM Tricky District - oop
hmSD
HM Pool District

Convert JSON response stream to string

I am trying to do a POST and then read the JSON response into a string.
I believe my issue is that I need to pass my own object into DataContractJsonSerializer but I'm wondering if there is some way to just get the response into an associative array or some sort of key/value format.
My JSON is formatted like: {"license":"AAAA-AAAA-AAAA-AAAA"} and my code is as follows:
using (Stream response = HttpCommands.GetResponseStream(URL, FormatRegistrationPost(name, email)))
{
string output = new StreamReader(response).ReadToEnd();
response.Close();
DataContractJsonSerializer json = new DataContractJsonSerializer(typeof(string));
MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(output));
string results = json.ReadObject(ms) as string;
licenseKey = (string) results.GetType().GetProperty("license").GetValue(results, null);
}
I'd strongly recommend looking into Newtonsoft.Json:
http://james.newtonking.com/pages/json-net.aspx
NuGet: https://www.nuget.org/packages/newtonsoft.json/
After adding the reference to your project, you just include the following using at the top of your file:
using Newtonsoft.Json.Linq;
And then within your method you can use:
var request= (HttpWebRequest)WebRequest.Create("www.example.com/ex.json");
var response = (HttpWebResponse)request.GetResponse();
var rawJson = new StreamReader(response.GetResponseStream()).ReadToEnd();
var json = JObject.Parse(rawJson); //Turns your raw string into a key value lookup
string license_value = json["license"].ToObject<string>();
you can do something like this using dictionary
Dictionary<string, string> values =
JsonConvert.DeserializeObject<Dictionary<string, string>>(json);
or something like this if you already know your object
var yourobject = JsonConvert.DeserializeObject<YourObject>(json);
with this tool
http://james.newtonking.com/projects/json/help/
reference here
Using JsonConvert.DeserializeObject to deserialize Json to a C# POCO class

Categories

Resources