Deserialize a json object with an array [duplicate] - c#

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);

Related

How to convert a JSON string array to XML correctly [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed last month.
Improve this question
I have a question about correctly representing a JSON string array in XML. I want to build the following JSON data (expected API input JSON):
{
"relatiesoort": [
"string"
],
"modifiedOn": "string",
"relatiecode": 0,
"naam": "string",
"vestigingsAdres": {
"contactpersoon": "string",
"straat": "string",
"postcode": "string",
"plaats": "string",
"land": {
"id": "00000000-0000-0000-0000-000000000000",
"uri": "string"
}
},
"correspondentieAdres": {
"contactpersoon": "string",
"straat": "string",
"postcode": "string",
"plaats": "string",
"land": {
"id": "00000000-0000-0000-0000-000000000000",
"uri": "string"
}
},
"telefoon": "string",
"mobieleTelefoon": "string"
}
I initially want to build this in XML format and then convert it to JSON. I initially build the following XML:
<?xml version="1.0" encoding="UTF-8" ?>
<root>
<relatiesoort>string</relatiesoort>
<modifiedOn>string</modifiedOn>
<relatiecode>0</relatiecode>
<naam>string</naam>
<vestigingsAdres>
<contactpersoon>string</contactpersoon>
<straat>string</straat>
<postcode>string</postcode>
<plaats>string</plaats>
<land>
<id>00000000-0000-0000-0000-000000000000</id>
<uri>string</uri>
</land>
</vestigingsAdres>
<correspondentieAdres>
<contactpersoon>string</contactpersoon>
<straat>string</straat>
<postcode>string</postcode>
<plaats>string</plaats>
<land>
<id>00000000-0000-0000-0000-000000000000</id>
<uri>string</uri>
</land>
</correspondentieAdres>
<telefoon>string</telefoon>
<mobieleTelefoon>string</mobieleTelefoon>
</root>
..... and then I use NewtonSoft.Json to translate it back to Json and feed it to the API.
But the problem is that if I convert it back to Json (this can also be done with this website: https://www.freeformatter.com/xml-to-json-converter.html) I get this result:
{
"relatiesoort": "string",
"modifiedOn": "string",
"relatiecode": "0",
"naam": "string",
"vestigingsAdres": {
"contactpersoon": "string",
"straat": "string",
"postcode": "string",
"plaats": "string",
"land": {
"id": "00000000-0000-0000-0000-000000000000",
"uri": "string"
}
},
"correspondentieAdres": {
"contactpersoon": "string",
"straat": "string",
"postcode": "string",
"plaats": "string",
"land": {
"id": "00000000-0000-0000-0000-000000000000",
"uri": "string"
}
},
"telefoon": "string",
"mobieleTelefoon": "string"
}
As you can see the 'relatiesoort field' is not a JSON array anymore and the API gives an error as the JSON is not in the expected format.
What I want is to build the XML in a way that the relatiesoort field remains a Json array after converting it back to JSON.
To accomplish that: should I format this field as followed in XML?:
<relatiesoort>
<element>klant</element>
</relatiesoort>
How can I accomplish this with the NewtonSoft.Json library?
Nothing points that relatiesoort is an array, You can't automatically convert string to array of strings, to convert automatically it shoud be
<relatiesoort>string</relatiesoort>
<relatiesoort>string</relatiesoort>
in this case you need c# class with an array xml attributes of relatiesoort property. So the only way to make it correct, you need to convert XML To c# and serialize to a json string. If you don't have the class, another way is to parse your json and correct the value
var jObj = JObject.Parse(json);
if (jObj["relatiesoort"].Type != JTokenType.Array)
{
jObj["relatiesoort"] = new JArray {jObj["relatiesoort"]};
json = jObj.ToString();
}
json
{
"relatiesoort": [
"string"
],
"modifiedOn": "string",
.....
}
You should take a look at this bit of doc
string json = #"...";
XmlDocument doc = (XmlDocument) JsonConvert.DeserializeXmlNode(json);
Now from what I see, vestigingsAdres and correspondentieAdres look as if they are the same type of class object, but given how NewtonSoft works, most likely they will not be grouped under a collection. I can foresee that you may want this to potentially be a Dictionary<string, yourObjHere> so if that is the case, you will need to intervene by constructing the objects in memory and then serializing to JSON. To do this, you can use JsonConvert.DeserializeObject<yourObj>(jsonString); if you have already modeled the class object
If you are fine with just straight up dumping to XML as is, then don't worry

Why is NewtonSoft not able to parse this json [duplicate]

This question already has answers here:
Error reading JObject from JsonReader. Current JsonReader item is not an object: StartArray. Path
(5 answers)
Closed 7 months ago.
When I go to online viewers, this shows as legal JSON,
stringstuff = "[
{
"data": {
"user": {
"email": "john#doe.com",
"external-id": "47b4-af36-e9fddecdb755"
},
"session-token": "BNIYdxZZew5KWnKHNZMjn8J3Q-Ii2q7Ifcs5klkginluGHhEalz-uA+C"
},
"context": "/sessions"
}
]";
but fails when I try
var jtoken = JObject.Parse(stringStuff)
with Exception:
Newtonsoft.Json.JsonReaderException: Error reading JObject from JsonReader. Current JsonReader item is not an object: StartArray. Path '', line 1, position 1.
at Newtonsoft.Json.Linq.JObject.Load(JsonReader reader, JsonLoadSettings settings)
at Newtonsoft.Json.Linq.JObject.Parse(String json, JsonLoadSettings settings)
at Newtonsoft.Json.Linq.JObject.Parse(String json)
at TastyWorksAPI.URLGetRestValues.<Authorize>d__2.MoveNext() in C:\Users\synct\OneDrive\Documents\Projects\API\API.cs:line 61
Your json string contains a json array, but you are trying to parse it as object, use JToken.Parse or JArray.Parse:
var jtoken = JArray.Parse(stringStuff);

How to get key value from input json in C# [duplicate]

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.

c# Parse JSON with no reference class? [duplicate]

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[][]>();

How to parse json value long character [duplicate]

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;

Categories