How to Parse Json data to normal data in C# - c#

I am beginner in c#, I have output from the website like {"result":"Invalid"} with my c# program, It seems to be Json ,I want to display these data as normal string and display it in message box and use those parsed data for validation
Program:
private async void Button_Click(object sender, RoutedEventArgs e)
{
var username = Username.Text;
var password = passbox .Password;
var postMessage = new StringContent(string.Format("username={0}&password={1}", username, password), Encoding.UTF8 , "application/x-www-form-urlencoded");
var response = await (new HttpClient()).PostAsync("http://xxx.xx.net/xx.php", postMessage);
var responseBody = await response.Content.ReadAsStringAsync();
MessageBox.Show( responseBody );
}
I want to know how to display the responseBody as normal string ?

Ideal solution depends on how complex Json string you got. If it has only single property-value pair like posted in question :
{"result":"Invalid"}
I think simple string manipulation logic will bring you the value ("Invalid") easily. Like this naive code :
var jsonString = "{\"result\":\"Invalid\"}";
//remove "{" and "}" from sting
var result = jsonString.Replace("{", "").Replace("}", "");
//separate property name from it's value
var pair = result.Split(':');
//property will contain property name : "result"
var property = pair[0];
//value will contain property value : "Invalid"
var value = pair[1];
Otherwise, if JSON response is more complex, it is not reliable to use string manipulation. I'd suggest to go with Newtonsoft.Json library as also suggested by #Mohammad.

Try using JSON.Net using below code if it returns result as output then
string json = responseBody;
JObject parsed = JObject.Parse(json);
string results = (string)parsed["result"];

Not too sure if this is the best approach... But I'm currently implementing something similar, and using a reader to... read the returned data.
System.IO.StreamReader reader = new System.IO.StreamReader(response.GetResponseStream());
string outputStr = reader.ReadToEnd();

To convert JSON object to string you should serialize it.
I'm using Newtonsoft.Json
After install above package you can use it as the following :
string jsonInString = JsonConvert.SerializeObject(responseBody);
MessageBox.Show(jsonInString);
And for convert json string to an object you can use the following :
ClassName obj = JsonConvert.DeserializeObject<ClassName>(jsonInString);

Related

How do I get a JSON object from a webpage

New to C#. I have a URL https://osu.ppy.sh/beatmapsets/781509#osu/1642274
with multiple json objects but I want to retrieve only the object with id="json-beatmapset" from this URL. This is my current piece of code:
string url = #"https://osu.ppy.sh/beatmapsets/781509#osu/1642274";
var code = new WebClient().DownloadString(url);
Console.WriteLine(code);
And I want to be able to extract information (for example the title) from this one json object using this:
dynamic dobj = JsonConvert.DeserializeObject<dynamic>(json);
string title = dobj["title"].ToString();
Console.WriteLine(title);
where json is the json object, which should print
Black Rover (TV Size)
How do I get the json object from this url?
As per my comment, you can use regular expressions to parse string data.
var json = Regex.Match(code, "<script id=\"json-beatmapset\".*?>(.*?)<\\/script>", RegexOptions.Singleline).Groups[1].Value;
dynamic dobj = JsonConvert.DeserializeObject<dynamic>(json);
string title = dobj["title"].ToString();
Console.WriteLine(title);

Get property from JSON by string name (already deserialized to class)

I'm using https://currencylayer.com/documentation , Free account's currency conversion API. I let user input output currency, so for example if user input SGD, It'll display the currency conversion for USD to SGD:"USDSGD":1.318504
The way to grab that value is to use dynamic deserializer, and put it to a label. like so:
lblResult.Text=test.quotes.USDSGD.ToString();
But what I want is to get the result regardless of the user selected currency. The other is always USD so I’d like to combine that and the user input currency to get the correct value from the API, like:
var propertyName = "USD" + destinationCurrencyName; // "USDSGD"
lblResult.Text=test.quotes.{propertyName}; // what I'd like
Here I would access the property "USDSGD".
I know that I can use reflection (Get property value from string using reflection in C#) but that seem to be overkill.
This is what the query returns:
{
"success":true,
"terms":"https:\/\/currencylayer.com\/terms",
"privacy":"https:\/\/currencylayer.com\/privacy",
"timestamp":1517629571,
"source":"USD",
"quotes":{
"USDSGD":1.318504
}
}
This is my code - strongly typed version indeed produces expected result, but I'd like to read name of currency (essentially property name of quotes element) from text box:
protected void btnConvert_Click(object sender, EventArgs e)
{
string convertTo = TextBox1.Text.ToString();
var webRequest = (HttpWebRequest)WebRequest.Create("http://apilayer.net/api/live?access_key=MY_ACCESS_KEY&currencies=" + Server.UrlEncode(convertTo) + "&source=USD&format=1");
var webResponse = (HttpWebResponse)webRequest.GetResponse();
if (webResponse.StatusCode == HttpStatusCode.OK)
{
JavaScriptSerializer json = new JavaScriptSerializer();
StreamReader sr = new StreamReader(webResponse.GetResponseStream());
var resString = sr.ReadToEnd();
//var test = JsonConvert.DeserializeObject<Result>(resString);
//lblResult.Text=test.quotes.USDSGD.ToString();
var test2 = JsonConvert.DeserializeObject<dynamic>(resString);
lblResult.Text = test2.quotes.USD+convertTo;
}
}
Currently my code
var test2 = JsonConvert.DeserializeObject<dynamic>(resString);
lblResult.Text = test2.quotes.USD+convertTo;
Returns the value:
SGD
Since the "convertTo" Variable happens to be "SGD".
I want the code to execute lblResult.Text = test2.quotes.USD+convertTo; not return me "convertTo" variable.
Now that I understand your question, you’re trying to concatenation string for accessing a value, not concatenation value and currency.
This can’t be done with dynamic and there’s no need. Deserialize to JObject and use its properties to get the values:
var test2 = JObject.Parse(resString);
var value = (test2[“quotes”] as JObject)[“USD” + convertTo];
Note that this doesn’t check that the data is valid. value is a JToken you can get the value from.
You will want to use JObject to go through the response object:
var response = JObject.Parse(resString);
var quotes = response["quotes"];
lblResult.Text = quotes[ "USD" + convertTo ].Value<string>().ToString();
The indexers of JObject allow you to index directly by strings, which gives you the ability to dynamically select the correct property the users wants.

Parsing JSON in c# return null value

I am trying to Parse Json in C# . (I am beginner in Json)
WebRequest webRequest = WebRequest.Create(url);
var httpWebRequest = (HttpWebRequest)webRequest;
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
String responseText = "";
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
responseText = streamReader.ReadToEnd();
}
//
This is Output in responseText :
{
"disclaimer": "Exchange rates provided for informational purposes only and do not constitute financial advice of any kind. Although every attempt is made to ensure quality, no guarantees are made of accuracy, validity, availability, or fitness for any purpose. All usage subject to acceptance of Terms: https://openexchangerates.org/terms/",
"license": "Data sourced from various providers; resale prohibited; no warranties given of any kind. All usage subject to License Agreement: https://openexchangerates.org/license/",
"timestamp": 1454497211,
"base": "EUR",
"rates": {
"INR": 74.42686146,
"USD": 1.0929332
}
}
To get the base from Json
var obj = JObject.Parse(responseText);
String bcur = (string)obj["base"];
Console.WriteLine("base :"bcur.ToString());
Output : base :EUR
similarly to get Rates of INR , I wrote
var obj = JObject.Parse(responseText);
String rte= (string)obj["INR"];
Console.WriteLine("rate:"rte);
it gives me null.
Can anyone tell me what is wrong in my code. or a better way to get the base and rate of the currency .
INR is not in the base object, so you are looking for the INR property in a place where it doesn't exist. You would have to go about it in a two step fashion in order to access the property in . Modifiying your code above, it would look something like this:
var obj = JObject.Parse(responseText);
JObject rates = (JObject)obj["rates"];
string rte = (string)rates["INR"];
Console.WriteLine("rate:" + rte);

json add new object to existing json file C#

I'm trying to automate the addition of new objects to an existing JSON file. I looked all around the web but only found adding data and stuff but not a whole object. This is how the file that I want to edit looks:
[
{"id":"123","name":"carl"}
]
and I want to go to
[
{"id":"123","name":"carl"},
{"id":"1234","name":"carl2"}
]
Thank you for all your answers but I don't think everyone completely understands what i mean I have tried some of the answers but then I get this:
[
"{\"id\":\"123\",\"name\":\"carl\"}"
]"{\"id\":\"1234\",\"name\":\"carl2\"}"
and I want everything in between the [].
If you use json.NET you can simply deserialize and serialize the json.
var list = JsonConvert.DeserializeObject<List<Person>>(myJsonString);
list.Add(new Person(1234,"carl2");
var convertedJson = JsonConvert.SerializeObject(list, Formatting.Indented);
Using Json.Net
//load from file
var initialJson = "[{\"id\":\"123\",\"name\":\"carl\"}]";
var array = JArray.Parse(initialJson);
var itemToAdd = new JObject();
itemToAdd["id"] = 1234;
itemToAdd["name"] = "carl2";
array.Add(itemToAdd);
var jsonToOutput = JsonConvert.SerializeObject(array, Formatting.Indented);
//save to file here
Using this method doesn't require strongly typed objects
You could replace this bit:
//load from file
var initialJson = "[{\"id\":\"123\",\"name\":\"carl\"}]";
With
var initialJson = File.ReadAllText(#"c:\myjson.json")
To load the json from a text file
A better performing solution than serializing/deserializing what may be a large file would be to open a FileStream, seek 1 character before the end, then serialize and write your new object into the array, then write a closing bracket. See this question C# How to delete last 2 characters from text file and write into the same line at the end my text?, I'll copy the code here - you already know how to serialize your object and encode it into bytes.
using(var fs = new FileStream("file.json")) {
fs.Seek(-1,SeekOrigin.End);
fs.Write(mySerializedJSONObjAsBytes,0,mySerializedJSONObjAsBytes.Length); // include a leading comma character if required
fs.Write(squareBracketByte, 0, 1);
fs.SetLength(fs.Position); //Only needed if new content may be smaller than old
}
Sorry haven't tested any of that, it's off the top of my head. Pro-tip: wrap FileStream in a StreamWriter so can write strings directly.
You could create a method:
public string AddObjectsToJson<T>(string json, List<T> objects)
{
List<T> list = JsonConvert.DeserializeObject<List<T>>(json);
list.AddRange(objects);
return JsonConvert.SerializeObject(list);
}
Then use it like this:
string baseJson = "[{\"id\":\"123\",\"name\":\"carl\"}]";
List<Person> personsToAdd = new List<Person>() { new Person(1234,"carl2") };
string updatedJson = AddObjectsToJson(baseJson, personsToAdd);
this would be a sample for you:
var list = JsonConvert.DeserializeObject<List<Example>>(json);
Example example = new Example();
example.name = "Product2";
example.id="1";
list.Add(example);
string output = JsonConvert.SerializeObject(list);
public class Example
{
public string id {get;set;}
public string name { get; set; }
}
I have been looking for a solution to this exact question for a week now. I finally figured out how to append it to the existing json array and not add it as a solo object after the array. Make sure you are using WriteAllText and not AppendAllText. Here is what I did:
JArray array = JsonConvert.DeserializeObject<JArray (jsonFile);
JObject obj = new JObject();
obj.Add("ID", "123");
obj.Add("Name", "Brian");
array.Add(obj);
var jsonToOutput = JsonConvert.SerializeObject(array, Formatting.Indented);
File.WriteAllText("fileName.json", jsonToOutput);

How to pass a variable in url in c#

I am trying to pass a string into a url in C#:
using (var client = new WebClient())
{
var responseStr = client.DownloadString("http://api.openweathermap.org/data/2.5 /weather?q=Groningen,nl&APPID=%207b030ffcc7338cc5f1adc4ca8e6205aa");
}
I there a way to pass a string variable, instead of ?q=Groningen
So I could use a text field to get the weather of a city.
I could not find the answer.
Thank you
In C# you can use + operator to concatenate strings.
So you can use something like following,
using (var client = new WebClient())
{
var responseStr = client.DownloadString("http://api.openweathermap.org/data/2.5 /weather?q="+CHOICE+",nl&APPID=%207b030ffcc7338cc5f1adc4ca8e6205aa");
}
CHOICE is the variable with your desired location.
More on concatenate : here
You could use string concatenation to do so:
var url = "http://.....q="+city+"&.....";
var responseStr = client.DownloadString(url);
where city is the variable that holds the city you want to pass.
Webclient client = new Webclient();
string city = "Lahore";
string appId = "123456789";
string url = "http://api.openweathermap.org/data/2.5/weather?APPID="+appId+"&q="+city+"";
var json = client.DownloadString(json);
Now de-serialize josn response as per your requirement.
Either using any way below
JavaScriptSerializer
JSON.Net library
DataContractJsonSerializer

Categories

Resources