I am using NewtonSoft's JSON.NET assembly to load a .json file in a C# console application. I think I have done most of the work except I am finding that some negative float values are being rounded.
Here is relevant code; as you can see, I have tried both load and parse methods but same results.
string content;
using (StreamReader reader = new StreamReader("C:\\[Path]\brackett_full_room.json"))
{
content = reader.ReadToEnd();
}
//// JObject rss = JObject.Load(reader);
JObject rss = JObject.Parse(content);
The original values are like:
"geometry" : { "rings" : [ [ [ -9221300.3411999997, 4120326.8838 ],
[ -9221300.2146000005, 4120327.992399998 ]...
But -9221300.3411999997 becomes something like -9221300.3412 in the rss variable and that is causing the coordinates to not work; the long positive values are fine.
Is there some way to keep precisions high enough (i.e. should have enough digits if parsed as double instead of float)?
Some code to Andrew's correct answer:
var settings = new JsonSerializerSettings();
settings.FloatParseHandling = FloatParseHandling.Decimal;
string json = #"{ ""rings"" : [ -9221300.3411999997, 4120326.8838 ] }";
var rss = JsonConvert.DeserializeObject(json, settings);
You need to use the Decimal type instead of a Double in order to keep that number of significant figures.
Related
I'M building Api that need to return json array as response like this :
"tagList": ["dragons", "training"],
But I got ((each element in separate line )):
"tagList": [
"dragons",
"training"
],
I was using System.Text.Json.Serialization;
I tried to change it to Json.net by JsonConvert.SerializeObject(obj) but I got the same result .
could anyone help me ,please ?
since you are using System.Text.Json.Serialization , try this
JsonSerializerOptions options = new JsonSerializerOptions();
options.WriteIndented = false //not using indent, white space, new line, etc.
string jsonString = JsonSerializer.Serialize(obj, options);
Why JArray.Parse(json_array) gives me "{" in front of the result? (it's like an object)
What I missed?
string _s = "[{\"person\": { \"b2b_pid\": \"157\"} }]";
JArray _j = JArray.Parse(_s);
_j returns:
{[
{
"person": {
"b2b_pid": "157"
}
}
]
}
string _s = "[{\"person\": { \"b2b_pid\": \"157\"} }]";
Simply because you are not passing grammatically correct json object.
in some cases,array cannot be the root of a json object,you have to use dictionary to wrap the array even when you only have one array in your json object.
PS: I notice there is new standard that array top lier is supported.However,be careful of code compatibility.
C# statement JArray.Parse(_s); is adequate intelligent to try to fix your json issue While Key missing.
I have an ugly JSON string that is getting returned from an API that looks like this (this is the result of Console.Write on the string):
{"d":"\"\\\"\\\\\\\"[{\\\\\\\\\\\\\\\"foo\\\\\\\\\\\\\\\":15,\\\\\\\\\\\\\\\"bar\\\\\\\\\\\\\\\":null}]\\\\\\\"\\\"\\n\""}
I am trying to parse this into a C# object in the simplest way possible, so I can access properties like foo and bar. But I am having a difficult time doing this.
I have tried parsing it a number of ways, including:
// code to get the response string
client.Headers.Add(HttpRequestHeader.ContentType, "application/json");
var serializedData = "{data: 'data'}";
var responseString = client.UploadString(url, "POST", serializedData);
// parse the response string
dynamic obj = Newtonsoft.Json.JsonConvert.DeserializeObject(jsonString);
This allows me to access the value of d, which is the actual string I need to parse. I then tried to parse that separately using JArray.Parse(obj["d"]), but I get an error saying that obj["d"] is not an array.
Unfortunately, I have no access to the API itself so can't modify how it's serializing the data it's returning.
Any suggestions?
You can replace all New Line, Backslash, Double quotes to format the JSON
var formattedJson = jsonString.Replace(#"\n", string.Empty)
.Replace(#"\", string.Empty)
.Replace("\"\"", string.Empty);
Console.WriteLine(formattedJson);
OUTPUT
{
"d": [
{
"foo": 15,
"bar": null
}
]
}
Convert to JArray.
var jArray = JArray.Parse(JObject.Parse(formattedJson)["d"].ToString());
Console.WriteLine($"{jArray[0]["foo"]} {jArray[0]["bar"]}");
OUTPUT
15
The problem is that the value of "d" is a string representing a string representing a string ... representing an array. You could call it JSON serialization "inception".
The way to deal with this is to deserialize the value corresponding number of times. If you're sure that the value is never going to be an actual string, you could do it like this, without having to know how many times the value was serialized:
var myObject = JObject.Parse(s);
var d = myObject["d"];
while(d.Type == JTokenType.String)
d = JToken.Parse(d.ToObject<string>());
myObject["d"] = d;
After this procedure myObject represents this data:
{
"d": [
{
"foo": 15,
"bar": null
}
]
}
Replacing escape characters in fine however I would not rely on the console.write command as the definitive output to examine. Here are a couple of other ways: -
Use Postman to make the API call so you can see the raw result. This will (hopefully) show it in an easy to read format that you can then define your class to deserialise to.
Write the raw response to a “.json” file. Open that file in a good editor (such as VS Code or VS itself) to see how the data is actually structured when it is received.
On a side note I would recommend using RestSharp to do the REST calls and Newtonsoft.Json to do the serialising/deserialising.
I have a string in this representation
{
transaction_id = 120,
transaction_shortname = 120. AUTO
}
It is not a Json representation i want to know if there is a simple way to transform it to Json representation like this:
{
"transaction_id": "120",
"transaction_shortname": "120. AUTO"
}
After that i can do the following to get a Transaction object:
JObject j = JObject.Parse("{\"transaction_id\": \"120\",\"transaction_shortname\": \"120. AUTO\"}");
transaction ttttt = JsonConvert.DeserializeObject<transaction>(j.ToString());
No, this can't be converted to JSON automatically, you need to parse the format you have manually. And I don't know any language which supports this syntax.
However, if you're absolutely sure there won't be some complex cases like quoted strings and "=" and "\"" in values, you can just apply regex:
Regex.Replace(
source.Replace("\r\n", "\n"),
#"(\n\s*)([^\n]*?)\s*=\s*([^\n]*?)([,\n])",
"$1\"$2\": \"$3\"$4")
The excerpt you've given qualifies as HJSON, and so can be parsed by any HJSON library. https://hjson.org/
Thanks for your response,
Lets say i have an object
object j ;
it's base is
{
transaction_id = 120,
transaction_shortname = 120. AUTO
}
I ended by doing the following :
transaction t = JsonConvert.DeserializeObject<transaction>(JsonConvert.SerializeObject(j));
I get an error while parsing a json string into an object. I am using system.json to parse the json string.
The JSON file: (NOTE: I cannot change the structure of this json file because it is generated)
{
title: "My Title",
log: "",
nid: "1234",
type: "software",
language: "EN",
created: "1364480345",
revision_timestamp: "1366803957",
body: {
und: [
{
value: "abc",
summary: "def"
}
]
}
}
The C# code:
string jsonString = new WebClient().DownloadString(".......MyJson.json"); //For test purpose
var obj = JsonObject.Parse (jsonString); ///<--- At this line the exception is thrown
The Exception:
System.ArgumentException has been thrown.
Invalid JSON string literal format. At line 1, column 2
How to solve this?
Thanks in advance!
You can't. That isn't valid json. Field names must be enclosed in quotes. All json parsing tools will throw when trying to parse that.
You could process it and turn it to valid json before deserializing, but really, you need to correct it API side. No clients will work with that.
How to solve this?
(NOTE: I cannot change the structure of this json file because it is generated)
Easy, use json.Net. it works without any problem with your json
var j = JObject.Parse(jsonString);
You can even use dynamic keyword
dynamic j = JObject.Parse(jsonString);
Console.WriteLine("{0},{1}", j.title, j.body.und[0].value);