Consider json string:
var json = "{\"myfield\":5e-0000006}";
I want deserialize that json, and get field "myfield" as raw string. Example:
JToken tok = <Deserialize> // how do this??
var val = tok["myfield"].ToString(); // need get "5e-0000006"
I need get EXACT string value that was in origin string ("5e-0000006" in example, but it may be any correct float string).
CodePudding user response:
Since you want an exact string and the json you have actually is a number (which means 5e-0000006
will equal 5e-6
) I would suggest using regex:
string json = "{\"myfield\":5e-0000006}";
Regex regex = new Regex("(?<=:)[^}] ");
string result = regex.Match(json).Value;
Explanation:
(?<=:)
look behind for a colon (:
)
[^}]
match any character not being a right curly brace (}
), one or more times.
That should give you the value as an exact string.
Update:
If you want to match based on the myfield
variable, you can expand the regex to contain that information:
string json = "{\"myfield\":5e-0000006}";
Regex regex = new Regex("(?<=\"myfield\":)[^}] ");
string result = regex.Match(json).Value;
Now you will only get the line where you have \"myfield\"
in front - in case you have many lines.
You can of course replace \"myfield\"
with a variable, like this:
string json = "{\"myfield\":5e-0000006}";
string myvar = "myfield";
Regex regex = new Regex("(?<=\"" myvar "\":)[^}] ");
string result = regex.Match(json).Value;
CodePudding user response:
With some info, and inspiration, from:
- You don't need to write any converters, just use the JRaw type as follows:
- Docs: This sample deserializes JSON to an object.
static void Main(string[] args)
{
var json = "{\"myfield\":5e-0000006}";
MyJson j = JsonConvert.DeserializeObject<MyJson>(json);
string mf = j.myfield;
Console.WriteLine(mf);
}
public class MyJson
{
[JsonProperty("myfield")]
public string myfield { get; set; }
}
This will output: 5e-0000006
And I am still wondering why I am not using JRaw
...