Convert JSON response stream to string - c#

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

Related

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

Convert string to json using C#

i am beginner to C#, i have a very long string and want to convert it to json, string is
{"employees":
[{"id":0,"level":0,"label":"Product Names","subitems":
[{"id":0,"level":1,"label":"Soren","subitemslevel3":
[{"id":0,"level":2,"label":"AAAA"},{"id":0,"level":2,"label":"bbb"}]},
{"id":0,"level":1,"label":"Test","subitemslevel3":
[{"id":0,"level":2,"label":"111"},{"id":0,"level":2,"label":"2222"}]}]},
\
any ideas?
You can do something like this:
var jobject = JsonConvert.DeserializeObject<JObject>(yourVariable);
this is using Newtonsoft's json library that you can get from nuget.
Also JObject is the C# equivalent to a JSON object so that's probably something you'll want to use.
u an also use,
JObject.Parse(urJsonString);
JObject is in Newtonsoft.Json.Linq namespace.
You need to Deserialize your string as follows :
// Your string here
string str = #"[{"categories":
[{"id":0,"level":0,"label":"Product Names","subitems":
[{"id":0,"level":1,"label":"Soren","subitemslevel3":
[{"id":0,"level":2,"label":"AAAA"},{"id":0,"level":2,"label":"bbb"}]},
{"id":0,"level":1,"label":"Test","subitemslevel3":
[{"id":0,"level":2,"label":"111"},{"id":0,"level":2,"label":"2222"}]}]},
{"id":0,"level":0,"label":"Product texts","subitems":
[{"id":0,"level":1,"label":""},{"id":0,"level":1,"label":"<p>Disney <strong>Princess<\/strong><\/p>\n"},{"id":0,"level":1,"label":"<p>Machines & Mechanisms - <strong>Middle<\/strong><\/p>\n"},{"id":0,"level":1,"label":"64738574"},{"id":0,"level":1,"label":"8765432"},{"id":0,"level":1,"label":"a"},{"id":0,"level":1,"label":"aa"},{"id":0,"level":1,"label":"ab"},{"id":0,"level":1,"label":"abe"},{"id":0,"level":1,"label":"aD!?"},{"id":0,"level":1,"label":"Bionicle"},{"id":0,"level":1,"label":"Disney Princess"},{"id":0,"level":1,"label":"er"},{"id":0,"level":1,"label":"foo foo"},{"id":0,"level":1,"label":"hej"},{"id":0,"level":1,"label":"igen"},{"id":0,"level":1,"label":"meta"},{"id":0,"level":1,"label":"metadata"},{"id":0,"level":1,"label":"metadata from kafka"},{"id":0,"level":1,"label":"Metatest"},{"id":0,"level":1,"label":"q"},{"id":0,"level":1,"label":"Simpsons"},{"id":0,"level":1,"label":"test"},{"id":0,"level":1,"label":"Test 123"},{"id":0,"level":1,"label":"Test Metadata 123"}]},{"id":0,"level":0,"label" :"Specialist Terms","subitems":[{"id":0,"level":1,"label":"meta"},{"id":0,"level":1,"label":"new category 1111"},{"id":0,"level":1,"label":"secret category"}]}]}]";
// DeSerialize your object
JavaScriptSerializer serializer1 = new JavaScriptSerializer();
object obje = serializer1.Deserialize(str, obj1.GetType());

Parsing through MSDN text?

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.

JavaScriptSerializer doesn't serialize DynamicJsonObject properly

I have a DynamicJsonObject like:
var obj = new DynamicJsonObject();
obj.Field1 = "field1";
obj.Field2 = "field2";
I need the obj's json string. I tried using JavaScriptSerializer:
var json = JavaScriptSerializer.Serialize(obj);
But the result is always json == '{}'
Is there a workaround for this? preferably not using third party libraries
You can add custom converter to JavaScriptSerializer. In System.Web.Helpers one already exists but is internal - you can use the following code to register it:
var type = Type.GetType("System.Web.Helpers.DynamicJavaScriptConverter, System.Web.Helpers");
var converter = (JavaScriptConverter)Activator.CreateInstance(type);
JavaScriptSerializer serializer = new JavaScriptSerializer();
serializer.RegisterConverters(new[] { converter });
var json = serializer.Serialize(obj);
or copy code from here
Thanks for your answers, but I've found a simple way to do this by using System.Web.Helpers.Json.
So, my code looks like this:
string json = Json.Encode(obj);
I cannot use an anonymous object, because I don't create obj, it is provided in the DynamicJsonObject 'format' already.

Deserializing variable Type JSON array using DataContractJsonSerializer

I have a JSON string in this form:
string jsonStr = "[\"A\", [\"Martini\", \"alovell\"],[\"Martin\", \"lovell\"]]"
I am trying to deserialize the JSON using the C# .NET deserializer DataContractJsonSerializer with the following code snippet
MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(jsonStr));
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof<X>);
X data = (X)serializer.ReadObject(ms);
Now since the JSON array is an array of variable types I do not know what type of object
X should be
If my String were
jsonStr = "[[\"Martini\", \"alovell\"],[\"Martin\", \"lovell\"]]"
I could use this:
X = List<List<String>>
and that would work for me. I was wondering if there is any way to deserialize variable type JSON array?
You could use Json.NET to do this.
JArray a = JArray.Parse(jsonStr);
The JArray would contain either strings or nested JArray's depending on the JSON.

Categories

Resources