How to fetch parameters by name (HttpWebResponse)? - c#

I have an object HttpWebResponse which do a request a get results correctly.
I fetch the parameters this way:
using (StreamReader streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
string result = streamReader.ReadToEnd();
return result;
}
However, is there a way to fetch a parameter value by giving a property the name?
Something like
string token = streamReader.GetValue("token");

If the response is JSON, you can use JSON.NET to deserialize/parse the text into an object and then access properties of the object. You can make use of a dynamic object so you don't have to define a type for serialization with JsonConvert.DeserializeObject. For example:
dynamic o = JsonConvert.DeserializeObject(result);
var token = o.token;

Related

Parse JSON object in C# without using class

I have two string values in a JSON object. I want to call this method in same class and use the values without using class.
I am using the following method:
public JsonResult Details()
{
return Json(new { Data = "DisplayName", result = "UniqueName" });
}
I need to use this data and result value in another method.
I am getting the value like:
var Details = JsonConvert.SerializeObject(Details());
My output is:
{
\"ContentEncoding\": null,
\"ContentType\": null,
\"Data\": {
\"Data\": \"DisplayName\",
\"result\": \"UniqueName\"
},
\"JsonRequestBehavior\": 1,
\"MaxJsonLength\": null,
\"RecursionLimit\": null
}
How do I get the data and result value from this?
The method which you are using (i.e:)
public JsonResult Details()
{
return Json(new { Data = "DisplayName", result = "UniqueName" });
}
returns a JsonResult object which has a property named Data, i.e Details().Data, which contains the data your object contains. So in order to get your object's Data and result values, you need to serialize it again.
This is the full solution:
JsonResult json = Details(); // returns JsonResult type object
string ser = JsonConvert.SerializeObject(json.Data); // serializing JsonResult object (it will give you json string)
object dec = JsonConvert.DeserializeObject(ser); // deserializing Json string (it will deserialize Json string)
JObject obj = JObject.Parse(dec.ToString()); // it will parse deserialize Json object
string name = obj["Data"].ToString(); // now after parsing deserialize Json object you can get individual values by key i.e.
string name = obj["Data"].ToString(); // will give Data value
string name = obj["result"].ToString(); // will give result value
Hope this helps.
By looking at JsonConvert.SerializeObject, I guess you are using NewtonSoft dll. In that you have JObject.Parse under Newtonsoft.Json.Linq which you can import (using Newtonsoft.Json.Linq;). You can parse that json string as
var details = JObject.Parse(your_json_string);
This will give you JObject and you can get the details as
var data = details["Data"].ToString();
JsonResult already stores the object for you, under Data. It has not been serialized yet, it simply indicates to the MVC framework to serialize it to JSON when responding to a web request.
var details = Details().Data;
Of course, this will be typed as an object - which isn't too useful. You can cast it back to the anonymous type like this:
private T CastToAnonymous<T>(object obj, T anonymousType)
{
return (T)obj;
}
var details = CastToAnonymous(Details().Data,
new { Data = string.Empty, result = string.Empty });
And then you can use it like...
var data = details.Data;
var result = details.result;
And it will be type-safe.

Convert Stream object to json object and then to user defined object

I call a service function which returns me a stream.
The stream contains an JSON object with two properties (Url and Status).
I want want to convert this JSON object into my user defined class called 'Response'. Response class has two properties Url and Status.
The code I have so far, but unclear what to do next or if I need to implement something else:
var response = _service.GetObject("Create");
var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
var jsonObject = serializer.DeserializeObject(response.ReadToEnd());
You can use the overload which takes a T generic type parameter and internally casts to the desired type:
Response jsonObject = serializer.DeserializeObject<Response>(response.ReadToEnd());
Note JavaScriptSerializer is deprecated. You should use Json.NET to work with JSON, which has the equivalent:
var response = _service.GetObject("Create");
var serializer = JsonConvert.DeserializeObject<Response>(response.ReadToEnd());

How to deserialize JSON object with json.net

StreamReader qryTmpltStream = new StreamReader(tmpltPath + "templates.json");
JsonTextReader qryTmpltReader = new JsonTextReader(qryTmpltStream);
JsonSerializer qryTmpltSrlzr = new JsonSerializer();
object jsonObject = qryTmpltSrlzr.Deserialize(qryTmpltReader);
var tplts = JsonConvert.DeserializeObject<JSONRepClass>(jsonObject);
In above code I'm trying to read in a json file then deserialize it into a class. The problem is, this: JsonConvert.DeserializeObject wants a string, but the Deserailize method call before it returns an object.
I tried casting to string and ToString(), but no go.
Anyone see what I'm missing here?
Try this, just read the json file contents into a string and deserialize it using Json.Net
var jSonString = File.ReadAllText(tmpltPath + "templates.json");
var tplts = JsonConvert.DeserializeObject<JSONRepClass>(jsonString);
This is the simplest way to use JSON.net to turn a json string into a strongly typed class.
YourClass myclass = new YourClass();
JsonConvert.PopulateObject(yourstring,myclass);

JObject how to read values in the array?

This is the json string:
{"d":[{"numberOfRowsAdded":"26723"}]}
string json = DAO.getUploadDataSummary();
JObject uploadData = JObject.Parse(json);
string array = (string)uploadData.SelectToken("d");
How do I change the code to reader the values in 'numberOfRowsAdded?
JObject uploadData = JObject.Parse(json);
int rowsAdded = Convert.ToInt32((string)uploadData["d"][0]["numberOfRowsAdded"])
You need to cast to JArray:
string json = "{\"d\":[{\"numberOfRowsAdded\":\"26723\"}]}";
JObject parsed = JObject.Parse(json);
JArray array = (JArray) parsed["d"];
Console.WriteLine(array.Count);
You can cast your JObject as a dynamic object.
You can also cast your array to JArray object.
JObject yourObject;
//To access to the properties in "dot" notation use a dynamic object
dynamic obj = yourObject;
//Loop over the array
foreach (dynamic item in obj.d) {
var rows = (int)item.numberOfRowsAdded;
}
I played around with writing a generic method that can read any part of my json string. I tried a lot of the answers on this thread and it did not suit my need. So this is what I came up with. I use the following method in my service layer to read my configuration properties from the json string.
public T getValue<T>(string json,string jsonPropertyName)
{
var parsedResult= JObject.Parse(json);
return parsedResult.SelectToken(jsonPropertyName).ToObject<T>();
}
and this is how you would use it :
var result = service.getValue<List<string>>(json, "propertyName");
So you can use this to get specific properties within your json string and cast it to whatever you need it to be.

How to cast json object into a string

Here i'm having json string and i wanted to get one perticular key and value from this json string.So I have used javascript serializer for that.
Below is the code which i have used in C#.Net.
string strProfile = fbApi.GetForStr("/statefarm/feed/");
var jss = new JavaScriptSerializer();
var dictionary = (IDictionary<string, object>)jss.DeserializeObject(strProfile);
object keyvalue = (object)dictionary["paging"];
string data = keyvalue.ToString();
When i do this I'm not able to fetch the keyvale pair from the jsonstring. If i write
string keyvalue = (string)dictionary["paging"];
instead of
object keyvalue = (object)dictionary["paging"];
string data = keyvalue.ToString();
getting on exception called
object of type 'system.object ' to type 'system.string '
What to do for this and how it can bne written.
I am assuming that you are using the Facebook API using some SDK / your custom code here. JSON.NET is the best way to go unless you don't want to end up in the unholy mess of Key Value paired JSON.
Try this.
var api = new FacebookClient
{
AccessToken = accessToken,
AppId = AppID,
AppSecret = AppSecret
};
dynamic result = api.Get("me/posts");
string JsonConvert.SerializeObject(result, new KeyValuePairConverter())
or to avoid confusion, simply add this to your code
object keyvalue = (object)dictionary["paging"];
JsonConvert.SerializeObject(keyvalue , new KeyValuePairConverter());
The NewtonSoft.Json.dll is also available as a Nuget package.

Categories