I was trying to insert nested Json string to existing Json string . Here's my json sample
JSON #1:
{
"Products":[
{
productId:1,
productName:"product1"
}
]
}
JSON #2:
{
"Brand":[
{
brandId:1,
brandName:"brand1"
}
]
}
Should be output
{
"Products":[
{
productId:1,
productName:"product1",
"Brand":[
{
brandId:1,
brandName:"brand1"
}
]
}
]
}
This is done thru c# code.Thankyou in advance
try this
using Newtonsoft.Json;
var jsonObj1=JObject.Parse(json1);
var jsonObj2=JObject.Parse(json2);
jsonObj1["Products"][0]["Brand"]=jsonObj2["Brand"];
string mergedJson=jsonObj1.ToString();
Console.WriteLine(mergedJson);
result
{
"Products": [
{
"productId": 1,
"productName": "product1",
"Brand": [
{
"brandId": 1,
"brandName": "brand1"
}
]
}
]
}
Related
I now need to deserialize a JSON that looks like this:
{
"arguments": {
"game": [
"--username",
"--version",
"--assetsDir",
{
"rules": [
{
"action": "allow",
"features": {
"is_demo_user": true
}
}
],
"value": "--demo"
},
{
"rules": [
{
"action": "allow",
"features": {
"has_custom_resolution": true
}
}
],
"value": [
"--width",
"--height"
]
}
]
}
}
As you can see, the array named "game" has both "value" and "object" in it. (But the fact is WORSE than this example, the number of elements is NOT certain)
And the data type of arguments.game[*].value is NOT certain, too.
I used to use classes to describe it, but deserialization failed.
Can't seem to describe an array with multiple element types with a class?
I am using Json.NET. Is there any way to deserialize this "game" array.
Thanks.
Is it a requirement to deserialize to an instance of a class? You could use an ExpandoObject:
using System.Dynamic;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
Console.WriteLine("Hello, World!");
string json = #"{
""arguments"": {
""game"": [
""--username"",
""--version"",
""--assetsDir"",
{
""rules"": [
{
""action"": ""allow"",
""features"": {
""is_demo_user"": true
}
}
],
""value"": ""--demo""
},
{
""rules"": [
{
""action"": ""allow"",
""features"": {
""has_custom_resolution"": true
}
}
],
""value"": [
""--width"",
""--height""
]
}
]
}
}";
var expConverter = new ExpandoObjectConverter();
dynamic obj = JsonConvert.DeserializeObject<ExpandoObject>(json, expConverter);
The obj variable will contain the result of the JSON conversion, then you can traverse the dynamic object in code.
For example, to get a list of strings under 'game':
IList<object> list = new List<object>(obj.arguments.game);
foreach (object str in list)
{
if (str as string != null)
{
Console.WriteLine(str as string);
}
}
This question already has answers here:
How to auto-generate a C# class file from a JSON string [closed]
(3 answers)
Closed 1 year ago.
I want to Deserialise this json file in my Xamarin android App to only get the coordinates.
{
"type": "FeatureCollection",
"features": [
{
"type": "Feature",
"id": "6849033",
"geometry": {
"type": "MultiPolygon",
"coordinates": [
[
[
[
6.562265,
40.36426
],
[
6.5622743,
40.3642745
],
[
6.5622944,
40.3642897
],etc...
Here is my approach with my class
public class Cadastre
{
public List<List<List<List<float>>>> coordinates { get; set; }
public Cadastre()
{
}
}
And finally here my code to Deserialize my json file
string responseFinished = await GetJson();
Cadastre c = JsonConvert.DeserializeObject<Cadastre>(responseFinished);
I tried many solutions but my coordinates are still null.
If anyone has a solution or a lead I would be grateful.
try this
var jsonObject=JObject.Parse(json);
var coordinates = ((JArray)jsonObject["features"][0]["geometry"]["coordinates"][0][0]).Select(c => new { One = c[0], Two = c[1]}).ToList();
result
[
{
"One": 6.562265,
"Two": 40.36426
},
{
"One": 6.5622743,
"Two": 40.3642745
},
{
"One": 6.5622944,
"Two": 40.3642897
}
]
or if you want to deserialize your way
List<List<List<List<float>>>> coordinates = ((JArray)jsonObject["features"][0]["geometry"]["coordinates"]).ToObject<List<List<List<List<float>>>>>();
result
[
[
[
[
6.562265,
40.36426
],
[
6.5622745,
40.364273
],
[
6.5622945,
40.36429
]
]
]
]
I have 3 levels of JSON object and trying to sort based on one of the inner-element.
Here is the sample JSON.
public class Program
{
public static void Main()
{
string myJSON = #"
{
""items"": ""2"",
""documents"": [
{
""document"": {
""libraryId"": ""LIB0001"",
""id"": ""100"",
""elements"": {
""heading"": {
""elementType"": ""text"",
""value"": ""My Heading 1""
},
""date"": {
""elementType"": ""datetime"",
""value"": ""2020-07-03T20:30:00-04:00""
}
},
""name"": ""My Name 1 "",
""typeId"": ""10ed9f3f-ab41-45a9-ba24-d988974affa7""
}
},
{
""document"": {
""libraryId"": ""LIB0001"",
""id"": ""101"",
""elements"": {
""heading"": {
""elementType"": ""text"",
""value"": ""My Heading 2""
},
""date"": {
""elementType"": ""datetime"",
""value"": ""2020-07-03T20:30:00-04:00""
}
},
""name"": ""My Name 2"",
""typeId"": ""10ed9f3f-ab41-45a9-ba24-d988974affa7""
}
}
]
}";
JObject resultObject = JObject.Parse(myJSON);
var sortedObj = new JObject(
resultObject.Properties().OrderByDescending(p => p.Value)
);
string output = sortedObj.ToString();
Console.WriteLine(output);
}
}
I would like to sort based the "date" field. Appreciate any help.
You can replace documents json array with sorted one using json path to sort it:
resultObject["documents"] = new JArray(resultObject["documents"]
.Children()
.OrderBy(p => p.SelectToken("$.document.elements.date.value").Value<DateTime>()));
Console.WriteLine(resultObject.ToString());
Or using indexer access:
resultObject["documents"] = new JArray( resultObject["documents"]
.Children()
.OrderBy(p => p["document"]["elements"]["date"]["value"].Value<DateTime>()));
Iam making a dictionary game in unity 3d. And i have a json file about all the definitions and examples of all vocabulary.Each word has key is the word it self ( which i highlighted). how can i get the value of each word(key). I have created an oject for json.
for example: i have a word "a cappella" it give me back:
a cappella
1: adverb
definition :without musical accompaniment
example : they performed a cappella
2 :adjective
definition :sung without instrumental accompaniment
example : they sang an a cappella Mass.
many thanks
Here is the model I use for the JSON
public class VocabularyModel : MonoBehavior
{
public string Word { get; set; }
public string WordId {get; set; }
public Meaning[] Meanings { get; set; }
public Label[] Labels { get; set; }
}
json String
{
"a cappella": {
"word": "a cappella",
"wordset_id": "5feb6f679a",
"meanings": [
{
"id": "492099d426",
"def": "without musical accompaniment",
"example": "they performed a cappella",
"speech_part": "adverb"
},
{
"id": "0bf8d49e2e",
"def": "sung without instrumental accompaniment",
"example": "they sang an a cappella Mass",
"speech_part": "adjective"
}
]
},
"AD": {
"word": "AD",
"wordset_id": "76c6ebfae9",
"meanings": [
{
"id": "4c21c72afa",
"def": "in the Christian era",
"speech_part": "adverb",
"synonyms": [
"A.D.",
"anno Domini"
]
}
]
},
"A.D.": {
"word": "A.D.",
"wordset_id": "b7e9d406a0",
"meanings": [
{
"id": "a7482f3e30",
"def": "in the Christian era",
"speech_part": "adverb",
"synonyms": [
"AD"
]
}
]
}
}
Are you using a library or you wrote the code yourself?
In the second case, I'd suggest to use Json.NET from Newtonsoft.
You can deserialize the JSON to a JObject and then treat it as if it was a dictionary.
To do this, you can structure your JSON in the following way:
{
"a_cappella" : {
"word" : "a cappella",
"wordId" : "123",
"meanings" : {...},
"labels" : {...}
}
"building" : {
"word" : "building",
"wordId" : "124",
"meanings" : {...},
"labels" : {...}
}
}
Then you deserialize into a JObject and search what you need:
var json = // here is your json string
var dictionary = JsonConvert.DeserializeObject(json);
if (dictionary.ContainsKey("a_cappella")){
return dictionary["a_cappella"].ToObject<VocabularyModel>();
}
It is necessary to write value of "Coordinates" property in json without hyphenation for the following lines, not using ToString() (without converting the value to a string). The desired result is shown below.
{
"Id": null,
"Style": "1234",
"Geometry": {
"Type": "Polygon",
"Coordinates": [[[47541.470259278358,6846.8710054924586],[47540.359922950891,6845.4552435801925],[47541.470259278358,6846.8710054924586]]],
"Properties": [
{
"PointType": "Straight"
},
{
"PointType": "Straight"
},
{
"PointType": "Straight"
}
]
}
}
but not:
{
"Id": null,
"Style": "1234",
"Geometry": {
"Type": "Polygon",
"Coordinates": "[[[47541.470259278358,6846.8710054924586],[47540.359922950891,6845.4552435801925],[47541.470259278358,6846.8710054924586]]]",
"Properties": [
{
"PointType": "Straight"
},
{
"PointType": "Straight"
},
{
"PointType": "Straight"
}
]
}
}
A function that serializes the corresponding class object in json:
JToken ToJson()
{
using (var writer = new JTokenWriter()) {
JsonSerializer serializer = new JsonSerializer();
serializer.Serialize(writer, this);
return writer.Token;
}
}
it seems your second case contains Coordinates property as serialized string.
why should not use
var string = JsonConvert.SerializeObject(YourObject) ?
But you should install https://www.nuget.org/packages/Newtonsoft.Json/ first
You could use string type for properties where you need double quotes and use array or number if you don't need it