How to Parse an example string in C# [duplicate] - c#

This question already has answers here:
Parse JSON in C#
(7 answers)
Closed 6 years ago.
I have this string
[
{
"url_short":"http:\/\/sample.com\/8jyKHv",
"url_long":"http:\/\/www.sample.com\/",
"type":0
}
]
What I want is to get http:\/\/sample.com\/8jyKHv and translate it to
http://sample.com/8jyKHv
Is it possible?

This string is JSON.
You can parse it by using JSON.NET.
Example:
using System;
using System.Collections.Generic;
using Newtonsoft.Json;
public class RootObject
{
public string url_short { get; set; }
public string url_long { get; set; }
public int type { get; set; }
}
public class Program
{
static public void Main()
{
string j = "[{\"url_short\":\"http:\\/\\/sample.com\\/8jyKHv\",\"url_long\":\"http:\\/\\/www.sample.com\\/\",\"type\":0}]";
List<RootObject> ro = JsonConvert.DeserializeObject<List<RootObject>>(j);
Console.WriteLine(ro[0].url_short);
}
}
Response:
http://sample.com/8jyKHv

Try this
Create a class like below
Note : you can use Paste Special option in visual studio to generate all the classes related to the JSON
Edit -> Paste Special -> Paste Json As Classes
it will create all the classes related to the JSON
public class url_details
{
public string url_short { get; set; }
public string url_long { get; set; }
public int type { get; set; }
}
public List<url_details> json_deserialized()
{
string json = "[{\"url_short\":\"http:\\/\\/sample.com\\/8jyKHv\",\"url_long\":\"http:\\/\\/www.sample.com\\/\",\"type\":0}]";
List<url_details> items = new List<url_details>();
items = JsonConvert.DeserializeObject<List<url_details>>(json);
return items;
}
And you can access the element like below
List<url_details> obj = json_deserialized();
string url_short = obj[0].url_short;

The JSON way is for sure recommended, but cant tell much about it. Here's the alternative way with regex:
Regex rgxUrl = new Regex("\"url_short\":\"(.*?)\",\"");
Match mUrl = rgxUrl.Match(yourString);
string url = Regex.Replace(mUrl.Groups[1].Value, #"\", "");

The string is a JSON string so you can create a class to get the values like this
public class Rootobject
{
public Class1[] Property1
{
get;
set;
}
}
public class Class1
{
public string url_short
{
get;
set;
}
public string url_long
{
get;
set;
}
public int type
{
get;
set;
}
}
After this class you can get the data like this
string json = "[{"url_short":"http:\/\/sample.com\/8jyKHv","url_long":"http:\/\/www.sample.com\/","type":0}]";
List<Rootobject> ro = JsonConvert.DeserializeObject<List<Rootobject>>(json);
string ururl = ro[0].Propert1[0].url_short;

Related

how to use JsonConvert.DeserializeObject for values without name [duplicate]

This question already has answers here:
How can I parse a JSON string that would cause illegal C# identifiers?
(3 answers)
Deserialize deeply Nested Json having one blank key using c#
(1 answer)
Closed 1 year ago.
I have a json string like this:
{"status":false,"data":{"errors":{"":"error45"}}}
I cant make a class for this json string, because the last part has no name => ""
I test this class:
public class Result
{
public bool status { set; get; }
public ResultDetail data { set; get; }
}
public class ResultDetail
{
public ErrorDetails errors { set; get; }
}
public class ErrorDetails
{
public string abc { set; get; }
}
but abc returns null !!!!
You can use the Dictionary<string, string> for the errors.
public class Result
{
public bool status { set; get; }
public ResultDetail data { set; get; }
}
public class ResultDetail
{
public Dictionary<string, string> errors { set; get; }
}
and use the following to deserialize and access the dictionary.
var result = JsonConvert.DeserializeObject<Result>(json);
Console.WriteLine(result.data.errors.Values.FirstOrDefault());
Or you can assign the value to a variable
obj.data.errors.TryGetValue("", out string error);
Console.WriteLine(error);
I will mention this as well that the property names should be Proper names (first letter Capital). To be able to deserialize properly, use the [JsonProperty("corresponding_json_key")] to each of your properties of your classes to conform to C# standards.
public class Result
{
[JsonProperty("status")]
public bool Status { set; get; }
[JsonProperty("data")]
public ResultDetail Data { set; get; }
}

Understanding how to bind a JSON string into a list of objects in C#?

I'm trying to convert a string into a list of objects in C#. I've written the following:
My input string is something of the following:
[{"channelID":"15","thresh":"30"},{"channelID":"28","thresh":"14"}]
I'm doing the convering using json.net
var deserializedResultList = JsonConvert.DeserializeObject<TriggerDataList>(result);
Now this is where I start to get hazy. I attempted the following class properties to no avail.
class TriggerDataList
{
[JsonProperty("Triggers")]
public List<TriggerData> Triggers { get; set; }
}
class TriggerData
{
public string channelID { get; set; }
public string thresh { get; set; }
}
Is it possible to bind that result to a List of TriggerData objects?
Since I tried your code on a clean solution, I will post exactly what I did as an answer rather than comment:
string json = "[{ \"channelID\":\"15\",\"thresh\":\"30\"},{ \"channelID\":\"28\",\"thresh\":\"14\"}]";
List<TriggerData> deserializedResultList = JsonConvert.DeserializeObject<List<TriggerData>>(json);
And the class (remember to make it public):
public class TriggerData
{
public string channelID { get; set; }
public string thresh { get; set; }
}
The above json (escaped for C#) worked and gave me 2 TriggerData objects in a list.

How to Deserialize the json object in windows phone 8.1?

I want to bind json obect to my properties When I deserialize the json object and bind into the properties ,properties shows null values,please some one help me to resolve this.
this is my code
string s = "{\"response\":{\"status\":\"fail\",\"content\":{\"user_id\":\"56\",\"first\":\"kiran\",\"last\":\"kumar\",\"username\":\"kirankumar\"},\"msg\":\"shggh\"}}";
var jsonObj = JObject.Parse(s);
response myDeserializedObj = (response)Newtonsoft.Json.JsonConvert.DeserializeObject(jsonObj.ToString(), typeof(response));
this is properties
public class response
{
public string status { get; set; }
public content content { get; set; }
}
public class content
{
public string user_id { get; set; }
public string first { get; set; }
public string last { get; set; }
public string username { set; get; }
}
Thanks,
karthik
I copied you code and tested it in my machine and I could solve your problem
here is the solution
add the following class
public class ResponseWrapper
{
public response response { get; set; }
}
replace your code with the following
string s = "{\"response\":{\"status\":\"fail\",\"content\":{\"user_id\":\"56\",\"first\":\"kiran\",\"last\":\"kumar\",\"username\":\"kirankumar\"},\"msg\":\"shggh\"}}";
response my = JsonConvert.DeserializeObject<ResponseWrapper>(s).response;
I am sure this will work.
UPDATE
Another solution (Which is tested also) and better than the first one
because it is more clean, and in this way you have not to create new wrapper class.
the solution is replace your string with the following string.
and all of your previous code will stay the same
here is the correct JSON string
string s = "{\"status\":\"fail\",\"content\":{\"user_id\":\"56\",\"first\":\"kiran\",\"last\":\"kumar\",\"username\":\"kirankumar\"},\"msg\":\"shggh\"}";
UPDATE 2
in the comments below of this answer you asked a completely a new question.
here is your new question (I copied this from your comments)
public class responseWraper
{
public response response { get; set; }
}
public class response
{
public string status { get; set; }
public content content { get; set; }
}
public class content
{
public Employees Employees { get; set; }
}
public class Employees
{
public string Employee_id { get; set; }
public string Employee_name { get; set; }
public string status { get; set; }
}
and here is how you are trying to deserialize this (also this copied from your comments)
string s = "{\"response\":{\"status\":\"success\",\"content\":{\"Employees\":[{\"Employee_i‌​d\":\"1\",\"Employee_name\":\"Sravan\",\"status\":\"1\"},}]}}}";
response my = Newtonsoft.Json.JsonConvert.DeserializeObject<responseWraper>(s).response;
ANSWER
your code has two problem
the first is you are using the Employees as array in the JSON string, but the type of the Employees property is not an array
the second problem that the JSON string itself is not valid. it has an errors
there is 4 { character but you have 5 } character inside it.
so you have to fix those two problem as the following
public class content
{
public List<Employees> Employees { get; set; }
}
and the string is
string s = "{\"response\":{\"status\":\"success\",\"content\":{\"Employees\":[{\"Employee_id\":\"1\",\"Employee_name\":\"Sravan\",\"status\":\"1\"},]}}}";
and if you have any other question , I will be happy to help you :)
Try your JSON with http://json2csharp.com/.
Your current code would deserialize the following JSON:
{
"status":"fail",
"content":{
"user_id":"56",
"first":"kiran",
"last":"kumar",
"username":"kirankumar"
},
"msg":"shggh"
}
You are missing a root class with a single Property "response" with the type "Response"

Deserialize CSV string to an C# Object

I have a response from Jira API, require to be deserialized into data model:
com.atlassian.greenhopper.service.sprint.Sprint#40675167[id=10151,rapidViewId=171,state=CLOSED,name=Sprint 37.1,startDate=2015-07-30T16:00:22.000+03:00,endDate=2015-08-13T16:00:00.000+03:00,completeDate=2015-08-13T14:31:34.343+03:00,sequence=10151]
This is actually the information of current sprint for issue.
I need to deserialize it to a model like:
public class Model
{
public string name { get; set; }
...
}
I have already removed all non-required information, like com.atlassian.greenhopper.service.sprint.Sprint#40675167 using Regex pattern \[(.*?)\] so I have brackets and all inside.
Now I stopped completely trying to find the a way to convert this string to a data model.
Found the following thread at the Atlassian Answers page and there appears to be no JSON representation of that inner Object. As shown in the example from that thread:
customfield_10007:[
"com.atlassian.greenhopper.service.sprint.Sprint#a29f07[rapidViewId=<null>,state=CLOSED,name=NORD - Sprint 42,startDate=2013-07-29T06:47:00.000+02:00,endDate=2013-08-11T20:47:00.000+02:00,completeDate=2013-08-14T15:31:33.157+02:00,id=107]",
"com.atlassian.greenhopper.service.sprint.Sprint#769133[rapidViewId=<null>,state=ACTIVE,name=NORD - Sprint 43,startDate=2013-08-14T15:32:47.322+02:00,endDate=2013-08-23T15:32:47.322+02:00,completeDate=<null>,id=117]"
],
The response is indeed a JSON array, but the array itself contains CSV's, so you can make use of the following to parse that:
public class DataObject
{
public string id { get; set; }
public string rapidViewId { get; set; }
public string state { get; set; }
public string name { get; set; }
public string startDate { get; set; }
public string endDate { get; set; }
public string completeDate { get; set; }
public string sequence { get; set; }
}
public class Program
{
private const string sampleStringData =
#"[id=10151,rapidViewId=171,state=CLOSED,name=Sprint 37.1,startDate=2015-07-30T16:00:22.000+03:00,endDate=2015-08-13T16:00:00.000+03:00,completeDate=2015-08-13T14:31:34.343+03:00,sequence=10151]";
static void Main(string[] args)
{
var dataObject = new DataObject();
string[][] splitted;
var sampleWithNoBrackets = sampleStringData.Substring(1,sampleStringData.Length-2);
splitted = sampleWithNoBrackets.Split(',').Select(p => p.Split('=')).ToArray();
dataObject.id = splitted[0][1];
dataObject.rapidViewId = splitted[1][1];
dataObject.state = splitted[2][1];
dataObject.name = splitted[3][1];
dataObject.startDate = splitted[4][1];
dataObject.endDate = splitted[5][1];
dataObject.completeDate = splitted[6][1];
dataObject.sequence = splitted[7][1];
Console.ReadKey();
}
}
Here's the output for the above:

Deserialize Json String not working

I want to deserialize a Json string from a php website. Unfortunately every time I try it, it will return null for medianPrice....Why?
public class PriceInfo
{
public string success { get; set; }
public double lowestPrice { get; set; }
public string volume { get; set; }
public string medianPrice { get; set; }
}
WebClient client = new WebClient();
string url = "http://steamcommunity.com/market/priceoverview/?country=US&currency=1&appid=730&market_hash_name=" + name;
byte[] html = client.DownloadData(url);
UTF8Encoding utf = new UTF8Encoding();
string return_value = utf.GetString(html);
PriceInfo priceInfo = new JavaScriptSerializer().Deserialize<PriceInfo>(return_value);
if( Double.Parse(priceInfo.medianPrice) > 0.15 )
{
string blablu = "hello";
}
The Json which returns from the website is the following:
{"success":true,"lowest_price":"$0.04","volume":"3,952","median_price":"$0.02"}
I hope you can help me!
I am strongly recommending that you try using Newtonsoft.Json
you will find that it is easier to handle your Jason objects
your code will be like this (Untested)
PriceInfo defaultCallResult = JsonConvert.DeserializeObject<PriceInfo>(return_value);
Your JSON property is named "median_price" (with an underscore), but your C# property is "medianPrice".
You could use Json.NET which will allow you to change the mapping using attributes.
Using Json.NET, decorate your medianPrice property as follows:
[JsonProperty(PropertyName = "median_price")]
public string medianPrice { get; set; }
I'm not sure how JavaScriptSerializer succeeds in parsing your class at all, as the keys hardly match match the class properties.
JavaScriperSerializer is obsolete, I'd recommend you use another serializer, such as Json.NET:
public class PriceInfo
{
[JsonProperty("success")]
public string Success { get; set; }
[JsonProperty("lowest_price")]
public double LowestPrice { get; set; }
[JsonProperty("volume")]
public string Volume { get; set; }
[JsonProperty("median_price")]
public string MedianPrice { get; set; }
}
And when you want to deserialize:
PriceInfo priceInfo = JsonConvert.DeserializeObject<PriceInfo>(returnValue);
First of all, as mentioned in the other answers, your property names do not match.
So take
public class PriceInfo
{
public string success { get; set; }
public string lowest_price { get; set; }
public string volume { get; set; }
public string median_price { get; set; }
}
edit: as mentioned by Yuval, you cannot use JsonProperty with JavaScriptSerializer so you need to stick with the property names from the json.
Then, there is currency information in the json. So you need to get rid of these:
string return_value = "{\"success\":true,\"lowest_price\":\"$0.04\",\"volume\":\"3,952\",\"median_price\":\"$0.02\"}";
string return_valueconverted = HttpUtility.HtmlDecode(return_value);
PriceInfo priceInfo = new JavaScriptSerializer().Deserialize<PriceInfo>(return_valueconverted);
priceInfo.lowest_price = priceInfo.lowest_price.TrimStart('$');
priceInfo.median_price = priceInfo.median_price.TrimStart('$');
As you can see, this does HtmlDecode these values and afterwards trims the dollar sign from the value.
See more about Html character set here:
http://www.w3.org/MarkUp/html-spec/html-spec_13.html

Categories