How to Parse a specific string in C# - c#

I have this structure:
{
"longUrl" :"http://www.sample.com",
"bok" :1,
"url" :"http://pleasegetme.com ",
"title" :""
}
//equivalent
"{
\n \"longUrl\" :\"http://www.sample.com/\",
\n \"bok\" :1,
\n \"url\" :\"http://pleasegetme.com \",
\n \"title\" :\"\"\n
}"
I have this function
public string Domain1Helper(string longText)
{
Regex rgxUrl = new Regex("\"url\":\"(.*?)\"");
Match mUrl = rgxUrl.Match(longText);
string url = Regex.Replace(mUrl.Groups[1].Value, #"\\", "");
return url;
}
What I want to get is http://pleasegetme.com.
What is the wrong in my Domain1Helper method?

What you have there is a JSON string. You can parse this using a library called Json.Net. You can find this as a nuget package. You can then use the following code to pick out the strings you want.
JObject jo = JObject.Parse(longtext);
Console.WriteLine(jo["longUrl"].Value.ToString()); // Outputs 'http://www.sample.com'

AJB, You have an error in your RegEx.
That being said you should use a JSON deserializer, like JSON.NET.
In the function Domain1Helper it should be:
Regex rgxUrl = new Regex("\"url\"\\s+:\"(.*?)\"");
Notice the \s+ ?

You have included the escape strings \. If you remove those, it should parse just fine, as in here:
https://regex101.com/r/hK7xR7/1
Note, that you method should look like this:
public string Domain1Helper(string longText)
{
Regex rgxUrl = new Regex(#"\"url\" :\"(.*?)\"");
Match mUrl = rgxUrl.Match(longText);
string url = Regex.Replace(mUrl.Groups[1].Value, #"\\", "");
return url;
}
And alternative solution would be using one json library, which is outlined here: https://msdn.microsoft.com/en-us/library/cc197957(v=vs.95).aspx

It is a freaking JSON formatted string. Use a JSON deserializer such as JSON.NET. I'll leave it to you on which one you'd want to use.
Here is the root object generated using json2csharp.com
public class RootObject
{
public string longUrl { get; set; }
public int bok { get; set; }
public string url { get; set; }
public string title { get; set; }
}
Example using JSON.NET:
using Newtonsoft.Json; // Namespace is something like this
string json = "{
\n \"longUrl\" :\"http://www.sample.com/\",
\n \"bok\" :1,
\n \"url\" :\"http://pleasegetme.com \",
\n \"title\" :\"\"\n
}";
RootObject rootObject = JsonConvert.DeserializeObject<RootObject>(json);
string url = rootObject.url;
// Do something with the url

Related

How to split this string {"username":"rob_sms","ipaddress":"127.0.0.1?","exp":1645954670.8374872} [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 12 months ago.
Improve this question
How to split this string:
string[] arr = {"username":"rob_sms","ipaddress":"127.0.0.1?","exp":1645954670.8374872}
I need to split like this:
string
string username = rob
string organinzationname = sms
string ipaddress = 127.0.0.1
string[] arr = { "username":"rob_sms","ipaddress":"127.0.0.1?","exp":1645954670.8374872};
This is not an array and not even valid c# syntex !! So the above line should give you a compiler error ... I thought you mean a JSON formatted string
string jsonText = "{\"username\":\"rob_sms\",\"ipaddress\":\"127.0.0.1?\",\"exp\":1645954670.8374872}";
and you can easily deserialize this JSON into c# object By define a class as following
public class Rootobject
{
public string username { get; set; }
public string ipaddress { get; set; }
public float exp { get; set; }
}
and then deserialze it as following
using System.Text.Json;
string jsonText = "{\"username\":\"rob_sms\",\"ipaddress\":\"127.0.0.1?\",\"exp\":1645954670.8374872}";
Rootobject obj = JsonSerializer.Deserialize<Rootobject>(jsonText);
Console.WriteLine($"user name: {obj.username}");
Console.WriteLine($"ip address: {obj.ipaddress}");
Console.WriteLine($"Exp: {obj.exp}");
Read more on How to serialize and deserialize JSON in .NET
What you posted is not array, it is json, so you can try this
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
var json= "{\"username\":\"rob_sms\",\"ipaddress\":\"127.0.0.1?\",\"exp\":1645954670.8374872}";
var jsonObject=JObject.Parse(json);
string userorganizname = (string) jsonObject["username"];
string username = userorganizname.Substring(0,userorganizname.IndexOf("_"));
string organinzationname =userorganizname.Substring(userorganizname.IndexOf("_")+1);
string ipaddress = (string) jsonObject["ipaddress"];
all you need is include Regex :
using System.Text.RegularExpressions;
then add this code to parse your string:
string text = "{\"username\":\"rob_sms\",\"ipaddress\":\"127.0.0.1?\",\"exp\":1645954670.8374872}";
string username = Regex.Match(text, "\"username\":\"(.*)\",\"ipaddress").Groups[1].Value;
string ipaddress = Regex.Match(text, "\"ipaddress\":\"(.*)\\?\",\"exp").Groups[1].Value;
put your input in text var.

How to use WebAPI post JSON values having "

public ActionResult<string> Post([FromBody] bot bot)
{
string jsonstr = JsonConvert.SerializeObject(bot);
return jsonstr;
}
public class bot
{
public string bot_id { get; set; }
public string bot_uid { get; set; }
}
Webapi post
JSON Params
{
"bot_id":"XX"XX"
}
if json value has ", how can I create a model to post webapi?
If this is about returning values
If bot id has a double quote in it the json serializer will escape it and there should be no problems.
I suspect you may be misreading the json. Some tools, including Visual Studio's Watch and Local Variables windows and the console window may show escaped " without the backslash and it may appear as if the string is { "bot_id":"XX"XX" } when in fact it's { "bot_id":"XX\"XX" }.
Also, is it possible that XX"XX is XX''XX (with two single quotes)?
In either case JsonCovert will serialise the string correctly.
If this is about consuming json
{ "bot_id":"XX"XX" } is a piece of invalid json.
I think there are two options here
Fix json (preferred)
Ask the poster to fix their payload.
Preprocess the json
You can accept json, fix known issues and only then feed it to the json deserialiser.
ActionResult<string> Post([FromBody] string botJson) // accept body as string
{
string fixedJson = fixMyJson(botJson);
var bot = JsonConvert.SerializeObject<Bot>();
...
Or
async Task<ActionResult<string>> Post()
{
HttpContent requestContent = Request.Content;
string botJson = await requestContent.ReadAsStringAsync();
string fixedJson = fixMyJson(botJson);
var bot = JsonConvert.DeserializeObject<Bot>(fixedJson);
...

How to get value from JSON objects in C#?

I've tried to get the values from the JSON object that I made a request from Google APIs. My goal is to get the data from transcript.
This is the JSON file.
{
"results": [
{
"alternatives": [
{
"transcript": "how old are you",
"confidence": 0.66882694
}
]
}
]
}
And I've tried to get the output by using this. But it doesn't work.
var result = ["result"][0]["alternative"][0]["transcript"].ToString()
When I query the data, It doesn't show anything, just empty string.
Convert your JSON to a class
Json2CSharp and you get:
public class Alternative
{
public string transcript { get; set; }
public double confidence { get; set; }
}
public class Result
{
public List<Alternative> alternatives { get; set; }
}
public class RootObject
{
public List<Result> results { get; set; }
}
Store it somewhere in your code.
Use Newtonsoft.Json package
Install Newtonsoft.Json NUGet Package in your solution and import it in your code:
using Newtonsoft.Json;
Now you can deserialize your json as you prefer as long as you have it in a string variable.
var yourObject = JsonConvert.DeserializeObject<RootObject>(jsonString);
You may access your transcript value using:
var transcript = yourObject.results[0].alternatives[0].transcript;
SOLUTION (without using external library like NewtonSoft.Json):
Add reference System.Web.Extensions.
use an assembly System.Web.Script.Serialization;
CODE:
var jsonString = "{\"results\": [ {\"alternatives\": [ {\"transcript\": \"how old are you\", \"confidence\": 0.66882694 } ] } ]}";
var jsonDeserialized = serializer.Deserialize<dynamic> (jsonString);
Console.WriteLine (jsonDeserialized["results"][0]["alternatives"][0]["transcript"]); // Prints "how old are you"
Your strings are JSON formatted, so you will need to parse it into a object. For that you can use JSON.NET.
Here is an example on how to parse a JSON string into a dynamic object:
string source = "{\r\n \"id\": \"100000280905615\", \r\n \"name\": \"Jerard Jones\", \r\n \"first_name\": \"Jerard\", \r\n \"last_name\": \"Jones\", \r\n \"link\": \"https://www.facebook.com/Jerard.Jones\", \r\n \"username\": \"Jerard.Jones\", \r\n \"gender\": \"female\", \r\n \"locale\": \"en_US\"\r\n}";
dynamic data = JObject.Parse(source);
Console.WriteLine(data.id);
.
Console which data you want show
Usually if I knew what the structure of the JSON looks like I would use class to parse it.
But you could always parse the string to JSON object anytime.
using Newtonsoft.Json.Linq;
var json=JObject.Parse(YOUR_JSON_STRING)
var result = json["results"][0]["alternative"][0]["transcript"].ToString()
https://dotnetfiddle.net/KSDcIP
Also your keys that you are requesting doesn't match the keys in the JSON

How to convert Json to Array c#

I have been trying to convert Json response to C# Array and the thing is Json goes up from my head I dont understand its structure as its a mess for me.
here is the example response I have as Json
{
"status":"ok",
"urls":{
"phone":[
{
"url":"tel:+9230154XXXXX",
"uri":"+9230154XXXXX"
}
],
"sms":{
"url":"sms:+9230154XXXXX",
"uri":"+9230154XXXXX"
},
"vcf":"https:\/\/www.eac.com\/i2\/ajax\/item\/vcf\/"
},
"limitExceeded":false
}
Now all i want from this Json sms:+9230154XXXXX this value.
I am using Newtonsoft.Json in this example.
Bellow is what I have tried so far
JObject jObject = JObject.Parse(json);
JToken jphone = jObject["urls"];
number = (string)jphone["phone"]["sms"];
Usage:
jObject["urls"]["phone"].ToObject<PhoneEntry[]>()
Class:
public class PhoneEntry {
[JsonProperty("url")]
public string Url { get; set; }
[JsonProperty("uri")]
public string Uri { get; set; }
}
I never really worked with Newtonsoft.Json but the following should work for you:
JToken token = JToken.Parse(json);
string number = (string)token.SelectToken("urls.sms.url")

Deserializing JSON when fieldnames contain spaces

I'm writing a tool to read JSON files. I'm using the NewtonSoft tool to deserialize the JSOn to a C# class. Here's an example fragment:
"name": "Fubar",
".NET version": "4.0",
"binding type": "HTTP",
The field names contain spaces and other characters (the .) that are invalid in C# identifiers.
What is the correct way to do this?
(Unfortunately I don't have the option of changing the JSON format.)
Use the JsonProperty attribute to indicate the name in the JSON. e.g.
[JsonProperty(PropertyName = "binding type")]
public string BindingType { get; set; }
System.Text.Json
If you're using System.Text.Json, the equivalent attribute is JsonPropertyName:
[JsonPropertyName(".net version")]
public string DotNetVersion { get; set; }
Example below:
public class Data
{
public string Name { get; set; }
[JsonPropertyName(".net version")]
public string DotNetVersion { get; set; }
[JsonPropertyName("binding type")]
public string BindingType { get; set; }
}
// to deserialize
var data = JsonSerializer.Deserialize<Data>(json);
Not sure why but this did not work for me. In this example I simply return a null for "BindingType" every time. I actually found it much easier to just download the Json result as a string and then do something like:
myString = myString.Replace(#"binding type", "BindingType")
You would do this as the step before deserializing.
Also was less text by a tad. While this worked in my example there will be situations where it may not. For instance if "binding type" was not only a field name but also a piece of data, this method would change it as well as the field name which may not be desirable.
If you want to initialize the Json manually, you can do:
var jsonString = "{" +
"'name': 'Fubar'," +
"'.NET version': '4.0'," +
"'binding type': 'HTTP'," +
"}";
var json = JsonConvert.DeserializeObject(jsonString);
return Ok(json);
Don't forget to include using Newtonsoft.Json;

Categories