This question already has answers here:
object to deserialize has a C# keyword
(4 answers)
Closed 7 years ago.
I will try to parse the string of JSON but there is a problem to parse 'long' character in JSON string.
JSON code is below
{ "valid": 1, "delta": 0, "time": 23755, "date": 200815, "fix": 2, "status": 1, "sats": 12, "lat": 37529922, "long": 126898053, "speed": 874, "heading": 0, "alt": 171300 }
I want to get lat and long value but I can't get value because Long character is keyword
My code is below
using (WebClient wc = new WebClient())
{
string json = wc.DownloadString(sb.ToString());
dynamic temp = JsonConvert.DeserializeObject(json);
Gps = new GpsInfo();
Gps.latY = temp.lat;
Gps.lonX = temp.long; //Error long type is keyword
SettingGpsChart(Gps);
}
How can I parse json value long and lat?
Use # symbol:
Gps.lonX = temp.#long;
And cast to your type:
Gps.lonX = (long)temp.#long;
Related
This question already has answers here:
JSON.NET JObject - how do I get value from this nested JSON structure
(1 answer)
JSon.NET deserialising subitems
(1 answer)
Json.NET get nested jToken value
(1 answer)
How to get a string value from a JToken
(4 answers)
Closed 1 year ago.
i have a json in below format
{{
"encoding_version": 1,
"root": {
"_type": "dictionary",
"test1": 0,
"test2": 6593,
"test3": ".key.test",
"test4": "key.test",
"test5": ".key.14",
"test6": 6159
}
}}
i am trying to get "test5" value which is 14
var data = (JObject)JsonConvert.DeserializeObject(inputJson);
var id = data["test5"];
however getting it null,Please help.
You have provide JSON with two times curl braces, i have made this small correction in your input JSON :
{
"encoding_version": 1,
"root": {
"_type": "dictionary",
"test1": 0,
"test2": 6593,
"test3": ".key.test",
"test4": "key.test",
"test5": ".key.14",
"test6": 6159
}
}
As your deserialization is correct and you are looking for value of "test5" which is ".key.14". Your desired key is two level down in JSON i.e. first go for "root" and then "test5". Hence your code will look like:
string test5Value = (string)result["root"]["test5"];
output => .key.14
If you want 14 then you might need to split output string and take out the required value.
This question already has answers here:
How can I deserialize JSON to a simple Dictionary<string,string> in ASP.NET?
(22 answers)
Closed 3 years ago.
I have a JSON similar to the following:
{
"type": "FeatureCollection",
"totalFeatures": "unknown",
"features": [
{
"type": "Feature",
"id": "xxx",
"geometry": {
"type": "MultiPolygon",
"coordinates": [
[
570389.865,
4722149.567
],
[
570389.865,
4722149.567
]
]
}
}
]
}
Is there a way to get the coordinates property of the first feature without using substring or parsing it to an class that represents that JSON?
I'm looking for something standard for handling JSON strings as an Object, with methods for getting childs by name or similar.
Any help would be appreciated
You can use Newtonsoft.Json library.
Here's example of getting coordinates field (using JSONPath):
var parsed = JObject.Parse(yourJson);
// returns JToken (but actually it's JArray, derived from JToken)
var coordArrayToken = parsed.SelectToken("$.features[0].geometry.coordinates");
var coordinates = coordArrayToken.ToObject<decimal[][]>();
Of course you can use simple indexers:
var parsed = JObject.Parse(yourJson);
// returns JToken (but actually it's JArray, derived from JToken)
var coordArrayToken = parsed["features"].Children().First()["geometry"]["coordinates"];
var coordinates = coordArrayToken.ToObject<decimal[][]>();
I'm trying to convert a string that is in the following format: 30,500 to convert to a float as 30.500 (in a json) So currently I have something like float.Parse(string.Format("{0:00,000}", inp_km.Text), CultureInfo.InvariantCulture.NumberFormat), but when I save it in json, it saves as 30500.00.
What am I doing wrong here?
How I just make it;
I make an object from the class Results like here;
team_results = new Results()
{
team_number = selected_team.team_number,
results = new Result[2] { new Result{ }, new Result { } }
};
Now when I add the new value to the json (example below) the input I get is 30,500
[
{
"team_number": 101,
"results": [
{
"given_start_time": "20:25",
"connection_to_start": "0:00",
"start_kp": "20:26",
"stop_kp": "0:0",
"missed_controls": 0,
"km": 0.000,
"gtks": [ "25:00", "30:15", "0:00" ]
},
{
"given_start_time": "21:56",
"connection_to_start": "0:00",
"start_kp": "21:57",
"stop_kp": "0:0",
"missed_controls": 0,
"km": 0.000,
"gtks": [ "25:00", "30:15" ]
}
]
}
]
But when it saves, it saves it as 30500.00
You are trying to execute Format on a string which will just yield the same string as a result.
You want to parse the string and pass an IFormatProvider implementation to the Parse method that "understands" what , and . mean in the string representation of the number being parsed.
In the example below I used the culture nl-NL which has the same meaning as what you expect in your question (. for separating thousands and , for separating the fractional part of the number).
const string inputText = "30,500";
var result = float.Parse(inputText, NumberStyles.AllowDecimalPoint, System.Globalization.CultureInfo.GetCultureInfo("nl-NL"));
Console.WriteLine("Parsed {0} to value {1}", inputText, result);
You can create custom NumberFormatInfo
var nf = new System.Globalization.NumberFormatInfo();
nf.NumberDecimalSeparator = ",";
nf.NumberGroupSeparator = " ";
and use it to Parse numeric value
Console.WriteLine(float.Parse("30,5000", nf));
Well , I have a solution but it would not be the best but it will work .
as you are working on a string you can use this function
string converter(string s)
{
s = s.Replace('.',',');
return s;
}
also check this link
https://msdn.microsoft.com/en-us/library/czx8s9ts(v=vs.110).aspx
This question already has answers here:
Deserializing JSON Object Array with Json.net
(6 answers)
Deserialize JSON with C#
(10 answers)
Closed 6 years ago.
i have a json object that has a json array that i would love to deserialize
{
"status": 1,
"loans": [
{
"loan_id": "686",
"client_id": "269",
"client_name": "Byaruhanga Guard",
"total_amount": "10000",
"min_amount": "10000",
"start_date": "2016-07-28 13:12:30",
"duration": "2",
"payment_interval": "day",
"voucher": "92",
"description": "FUEL",
"when_added": "2016-07-28 13:12:30",
"approval_status": "approved",
"total_paid": null,
"next_payment_date": "2016-07-29 10:12:30"
}
]
}
please help.
use Newtonsoft.Json from NuGet package
var results= JsonConvert.DeserializeObject<string[]>(jsondata);
var loanjson=results["loans"];
var loandata= JsonConvert.DeserializeObject<string[]>(loanjson);
I tried using Newtonsoft.Json to deserialize this json string, but I'm not getting the desired output.
my json string is
[
{
"id": 1,
"key": "Residential Homeowner",
"i18nText": "unknown message code DB_ENUM_UserType_residentialhomeowner",
"i18nKey": "DB_ENUM_UserType_residentialhomeowner"
},
{
"id": 8,
"key": "VAR Dealer \/ Builder",
"i18nText": "unknown message code DB_ENUM_UserType_vardealer\/builder",
"i18nKey": "DB_ENUM_UserType_vardealer\/builder"
},
{
"id": 2,
"key": "Administrator",
"i18nText": "unknown message code DB_ENUM_UserType_administrator",
"i18nKey": "DB_ENUM_UserType_administrator"
},
{
"id": 9998,
"key": "TempGuidUser",
"i18nText": "unknown message code DB_ENUM_UserType_tempguiduser",
"i18nKey": "DB_ENUM_UserType_tempguiduser"
},
{
"id": 9999,
"key": "GuidUser",
"i18nText": "unknown message code DB_ENUM_UserType_guiduser",
"i18nKey": "DB_ENUM_UserType_guiduser"
}
]
I just want the value of key when value of id=1. Generally json starts with {}(curly bracket) but here it is like [](square bracket). I've seen many examples but none worked for me.
Generally json starts with {} (curly bracket), but here it is like [] (square bracket).
This is because you got an array of objects, not a single object. Arrays are serialized with square brackets around them. You should deserialize it into an array, and then grab the object at the index of interest.
This is a related post that addresses JSON parsing in C#: C# JSON Parsing.
If the brackets are a problem, simply use:
string json = inputJson.Trim().Trim('[',']');
If the id can have a minimum value of 1, then this should work:
string GetKey(string inputJson)
{
string key = inputJson.Substring(inputJson.IndexOf("key")+5);
key = key.Substring(key.IndexOf("\""), key.IndexOf(",")-key.IndexOf("\""));
key = key.Trim('\"');
return key;
}
If you are only interested in a single value from that larger JSON value, you may want to try Linq to JSON which would allow you to query over the JSON without deserializing everything.
Example:
JArray values = JArray.Parse(json);
string key;
var keyObject = values.FirstOrDefault(p => (int)p["id"] == 1);
if (keyObject != null)
{
key = (string)keyObject["key"];
}
[] is to define a json object array. Your output should be an array. Traverse through the array like:
for(var i=0; i<output.Length; i++)
{
if(output[i].id == "1") // desired id
{
Console.WriteLine(output[i].key);// use it as you wish
}
}
and use the found objects key.