Changing object element within json - c#

I have JSON like this
{
"amounts": [
{
"tid": 7072,
"amount": 10000,
"currency": "USD"
},
{
"tid": 7072,
"amount": 4000,
"currency": "USD"
}
],
"status": 0,
"errorCode": 0
}
I need to retrieve amount value from this JSON and to divide for example in 10. After that i would like to replace amount value in original json . How can i do this? I am using .Net json tools like NEwtonsoft json.

private string DivideAmounts(string str, int denominator)
{
var obj = (JObject)JsonConvert.DeserializeObject(str);
foreach (var amount in obj["amounts"])
{
var value = amount.Value<int>("amount");
var newValue = value / denominator;
amount["amount"] = newValue;
}
return obj.ToString();
}
Using Newtonsoft.Json.
Add check of argument "denominator" to avoid divide-by-zero error.

Use the following tool to generate classes:
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp11
{
class Program
{
static void Main(string[] args)
{
var js = "{\"amounts\": [ { \"tid\": 7072, \"amount\": 10000, \"currency\": \"USD\" }, { \"tid\": 7072, \"amount\": 4000, \"currency\": \"USD\" } ], \"status\": 0, \"errorCode\": 0}";
var obj = Welcome.FromJson(js);
for (int i = 0; i < obj.Amounts.Length; i++)
{
obj.Amounts[i].AmountAmount /= 10;
}
var newjs = Serialize.ToJson(obj);
Console.WriteLine(newjs);
Console.ReadKey();
}
}
public partial class Welcome
{
[JsonProperty("amounts")]
public Amount[] Amounts { get; set; }
[JsonProperty("status")]
public long Status { get; set; }
[JsonProperty("errorCode")]
public long ErrorCode { get; set; }
}
public partial class Amount
{
[JsonProperty("tid")]
public long Tid { get; set; }
[JsonProperty("amount")]
public long AmountAmount { get; set; }
[JsonProperty("currency")]
public string Currency { get; set; }
}
public partial class Welcome
{
public static Welcome FromJson(string json) => JsonConvert.DeserializeObject<Welcome>(json, Converter.Settings);
}
public static class Converter
{
public static readonly JsonSerializerSettings Settings = new JsonSerializerSettings
{
MetadataPropertyHandling = MetadataPropertyHandling.Ignore,
DateParseHandling = DateParseHandling.None,
Converters = {
new IsoDateTimeConverter { DateTimeStyles = DateTimeStyles.AssumeUniversal }
},
};
}
public static class Serialize
{
public static string ToJson(this Welcome self)
{
return JsonConvert.SerializeObject(self, Converter.Settings);
}
}
}

Generate quicktype from json2csharp like
public class Amount
{
public int tid { get; set; }
public int amount { get; set; }
public string currency { get; set; }
}
public class RootObject
{
public List<Amount> amounts { get; set; }
public int status { get; set; }
public int errorCode { get; set; }
}
1) First of all deserialize your json string to RootObject
2) Iterate over on amounts property in RootObject.
3) Make arithmetic operation on your amount like divide by 10.
4) Serialize again your RootObject.
Here I create a console app for your demonstration purpose that shows how above steps will be executed.
class Program
{
static void Main(string[] args)
{
string inputJson = #"{'amounts':[{'tid':7072,'amount':10000,'currency':'USD'},{'tid':7072,'amount':4000,'currency':'USD'}],'status':0,'errorCode':0}";
RootObject rootObject = JsonConvert.DeserializeObject<RootObject>(inputJson);
foreach (var item in rootObject.amounts)
{
item.amount = item.amount / 10;
}
//OR you can do it with shorter version of foreach
//rootObject.amounts.ForEach(x => x.amount = x.amount / 10);
string outputJson = JsonConvert.SerializeObject(rootObject);
Console.WriteLine(outputJson);
Console.ReadLine();
}
}
Output:

Related

How do I call JSON in a simplified manner

I am connecting to an external API which seems to be returning JSON
using (var client = new APIClient())
{
var data = client.General.GetAccountInfo().Data.Balances;
}
When I move over .Data.Balances, it shows:
IEnumerable<API.Net.Objects.Spot.SpotData.APIBalance>
API.Net.Objects.Spot.SpotData.APIAccountInfo.Balances { get; set; }
List of assets and their current balances
Here is an extract of the JSON data:
"balances":[
{
"asset":"ABC",
"free":"0.00000000",
"locked":"0.00000000"
},
{
"asset":"DEF",
"free":"0.00000000",
"locked":"0.00000000"
},
{
"asset":"GHI",
"free":"0.00000000",
"locked":"0.00000000"
}
]
How do I make use of this data so if I type console.writeline(data[0]["asset"]), it gives me ABC?
This seems to be the simplist solution:
using System.Linq;
using (var client = new APIClient())
{
var data = client.General.GetAccountInfo().Data.Balances.ToList();
Console.WriteLine(data[0].asset);
Console.WriteLine(data[0].free);
Console.WriteLine(data[0].locked);
}
Hy,
From the sample file you can create a class ´balance »
Public class balance
{
Public string asset {get; set;}
Public Free .......
Public Locked .....
}
And then you can use Json.net
To deserialize the JSon file
public void serializejson()
{
List balances = JsonConvert.DeserializeObject<List>(data);
}
}
using System;
using System.Collections.Generic;
using System.IO;
using System.Text.Json;
using System.Text.Json.Serialization;
namespace Game
{
public class Balance
{
[JsonPropertyName("asset")]
public string Asset { get; set; }
[JsonPropertyName("free")]
public string Free { get; set; }
[JsonPropertyName("locked")]
public string Locked { get; set; }
}
public class Root
{
[JsonPropertyName("balances")]
public List<Balance> Balances { get; set; }
}
class Program
{
static void Main(string[] args)
{
var data = File.ReadAllText("test.json");
var deserialized = JsonSerializer.Deserialize<Root>(data);
var balances = deserialized.Balances;
// Don't iterati in such a way! Use foreach instead.
for (int i = 0; i < balances.Count; i++)
{
Console.WriteLine($"{balances[i].Asset} {balances[i].Free} {balances[i].Locked}");
}
foreach (var balance in balances)
{
Console.WriteLine($"{balance.Asset} {balance.Free} {balance.Locked}");
}
}
}
}
You can use this code for you:
public class Balance {
public string asset { get; set; }
public string free { get; set; }
public string locked { get; set; }
}
public class Root {
public List<Balance> balances { get; set; }
}
And for deserialize:
using (var client = new APIClient())
{
var data = client.General.GetAccountInfo().Data.Balances;
Root myDeserializedClass = JsonConvert.DeserializeObject<Root>(data);
Console.WriteLine(myDeserializedClass.balances[0].asset);
}

create c# class for json string which have number as variables in object

I have to pass following JSON format to the REST api.
"weconnect_validate":{
"Row":[
{"0":"44063fe6-fe22-11ea-bb30-005056923098::TEST10800::9888880470","1":"TEST10800"}
]
}
Now problem occurring here is that how i create class for
Row with variable name 0 and 1.
I have tried following
public class BasicRow
{
[JsonProperty("0")]
public string Zero { get; set; }
[JsonProperty("1")]
public string One { get; set; }
}
public class Weconnect_Validate
{
public BasicRow[] rows { get; set; }
}
but it is not working. In debug mode it is passing
Row:[{"Zero":......
Please suggest some tricks or different way to create c# class.
Edit
Following json object i need to send to REST api using http client .
{"PWSESSIONRS":{"PWPROCESSRS":{"PWDATA":{"weconnect_validate":{"Row":[{"0":"dc9a2d38-fe28-11ea-bb30-005056923098","1":"TEST10800"}]}},"PWHEADER":{"LOGIN_ID":"TEST10800","ORG_ID":"HSA","APP_ID":"HSA","IN_PROCESS_ID":"1","OUT_PROCESS_ID":"weconnect_validate"}}}}
My question is how to build c# classes for this type of json string or object.
QuickType.io suggested this, which is what my first thought was (Array of Dictionary<string, string>) given that your assertion that JsonProperty wasn't working:
namespace SomeNamespaceHere
{
using System;
using System.Collections.Generic;
using System.Globalization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
public partial class RootClassNameHere
{
[JsonProperty("weconnect_validate")]
public WeconnectValidate WeconnectValidate { get; set; }
}
public partial class WeconnectValidate
{
[JsonProperty("Row")]
public Dictionary<string, string>[] Row { get; set; }
}
public partial class RootClassNameHere
{
public static RootClassNameHere FromJson(string json) => JsonConvert.DeserializeObject<RootClassNameHere>(json, SomeNamespaceHere.Converter.Settings);
}
public static class Serialize
{
public static string ToJson(this RootClassNameHere self) => JsonConvert.SerializeObject(self, SomeNamespaceHere.Converter.Settings);
}
internal static class Converter
{
public static readonly JsonSerializerSettings Settings = new JsonSerializerSettings
{
MetadataPropertyHandling = MetadataPropertyHandling.Ignore,
DateParseHandling = DateParseHandling.None,
Converters =
{
new IsoDateTimeConverter { DateTimeStyles = DateTimeStyles.AssumeUniversal }
},
};
}
}
But I didn't actually encounter any problems using your proposed route:
with this code:
public class Row
{
[JsonProperty("0")]
public string Zero { get; set; }
[JsonProperty("1")]
public string One { get; set; }
}
public class WeconnectValidate
{
public List<Row> Row { get; set; }
}
public class Root
{
[JsonProperty("weconnect_validate")]
public WeconnectValidate WeconnectValidate { get; set; }
}
Used like:
var x = JsonConvert.SerializeObject(new Root()
{
WeconnectValidate = new WeconnectValidate()
{
Row = new List<Row>(){
new Row() { Zero = "a", One = "b" },
new Row() { Zero = "c", One = "d" }
}
}
});
With the latest Newtonsoft.Json

C# receiving json string but unable to deserialize it

i have an application that has to deserialize an array of data wrapped in a "results" Root Object, using Netwonsoft.Json package from NuGet
The Json string is exactly this:
{"results":[{"Coin":"SBD","LP":0.000269,"PBV":-54.36,"MACD1M":true,"MACD30M":true,"MACD1H":true,"MACD1D":true},{"Coin":"XMR","LP":0.027135,"PBV":11.44,"MACD1M":true,"MACD30M":true,"MACD1H":true,"MACD1D":true}]}
This Json string is created from a Console App i made, i wanted it to look like this https://bittrex.com/Api/v2.0/pub/market/GetTicks?marketName=BTC-NEO&tickInterval=hour
My class looks like this
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace WindowsFormsApp2
{
public class Result
{
public string Coins { get; set; }
public decimal LastPrice { get; set; }
public decimal PercentBuyVolume { get; set; }
}
public class RootObject
{
public List<Result> results { get; set; }
}
}
In the Main form i have a function to download from a URL that Json (i have XAMPP running Apache) and deserialize it in an array. And it looks like this:
private void DownloadBittrexData()
{
int PanelID = 0;
var Coin = new List<string>();
var LastPrice = new List<decimal>();
var PercentBuyVolume = new List<decimal>();
var MACD1M = new List<bool>();
var MACD30M = new List<bool>();
var MACD1H = new List<bool>();
var MACD1D = new List<bool>();
var client = new WebClient();
var URL = client.DownloadString("http://localhost/test.json");
Console.WriteLine("Json String from URL: " + URL);
var dataDeserialized = JsonConvert.DeserializeObject<RootObject>(URL);
foreach (var data in dataDeserialized.results)
{
Coin.Add(data.Coins);
LastPrice.Add(data.LastPrice);
PercentBuyVolume.Add(data.PercentBuyVolume);
}
int sizeOfArrayClose = Coin.Count - 1;
for (int i = 0; i <= sizeOfArrayClose; i++)
{
Console.WriteLine("Coin: " + Coin[i]);
Console.WriteLine("Lastprice: " + LastPrice[i]);
Console.WriteLine("PBV: " + PercentBuyVolume[i]);
}
}
Newtonsoft.Json is of course declared at the beginning of the form together with System.Net
using System.Net;
using Newtonsoft.Json;
The output looks like this:
Json String from URL: {"results":[{"Coin":"SBD","LP":0.000269,"PBV":-54.36,"MACD1M":true,"MACD30M":true,"MACD1H":true,"MACD1D":true},{"Coin":"XMR","LP":0.027135,"PBV":11.44,"MACD1M":true,"MACD30M":true,"MACD1H":true,"MACD1D":true}]}
Coin:
Lastprice: 0
PBV: 0
Coin:
Lastprice: 0
PBV: 0
It's like it fails to deserialize it after downloading it.
What should i do? Thank you very much.
Your property names don't map to the field names in the JSON. You could rename your C# properties to match the JSON, but it would make for unreadable downstream code.
Instead, you should map your properties (with nice, readable names) to the names that appear in the JSON, using JsonPropertyAttribute:
public class Result
{
public string Coin { get; set; } //didn't bother here: changed property name to Coin
[JsonProperty("LP")]
public decimal LastPrice { get; set; }
[JsonProperty("PBV")]
public decimal PercentBuyVolume { get; set; }
}
your model should be like this for deserialize json
public class Result
{
public string Coin { get; set; }
public double LP { get; set; }
public double PBV { get; set; }
public bool MACD1M { get; set; }
public bool MACD30M { get; set; }
public bool MACD1H { get; set; }
public bool MACD1D { get; set; }
}
public class RootObject
{
public List<Result> results { get; set; }
}
LastPrice and PercentBuyVolume are not available in your model that's the reason it's getting an error.
I tried your exact code on my system and I was able to retrieve the result as expected. Hope this helps, It's easy to understand.
Here is the main class
static void Main(string[] args)
{
RootObject configfile = LoadJson();
foreach (var tResult in configfile.results)
{
Console.WriteLine("Coin: " + tResult.Coin);
Console.WriteLine("Lastprice: " + tResult.LP);
Console.WriteLine("PBV: " + tResult.PBV);
}
Console.ReadLine();
}
LoadJson Function would be
private static RootObject LoadJson()
{
string json = "{\"results\":[{\"Coin\":\"SBD\",\"LP\":0.000269,\"PBV\":-54.36,\"MACD1M\":true,\"MACD30M\":true,\"MACD1H\":true,\"MACD1D\":true},{\"Coin\":\"XMR\",\"LP\":0.027135,\"PBV\":11.44,\"MACD1M\":true,\"MACD30M\":true,\"MACD1H\":true,\"MACD1D\":true}]}";
RootObject configs = Deserialize<RootObject>(json);
return configs;
}
and Deserialize function would be
private static T Deserialize<T>(string json)
{
T unsecureResult;
string _DateTypeFormat = "yyyy-MM-dd HH:mm:ss";
DataContractJsonSerializerSettings serializerSettings = new DataContractJsonSerializerSettings();
DataContractJsonSerializer serializer;
MemoryStream ms;
unsecureResult = default(T);
serializerSettings.DateTimeFormat = new System.Runtime.Serialization.DateTimeFormat(_DateTypeFormat);
serializer = new DataContractJsonSerializer(typeof(T));
ms = new MemoryStream(Encoding.Unicode.GetBytes(json));
unsecureResult = (T)serializer.ReadObject(ms);
return unsecureResult;
}
and Now your Datamodel would be
public class Result
{
public string Coin { get; set; }
public double LP { get; set; }
public double PBV { get; set; }
public bool MACD1M { get; set; }
public bool MACD30M { get; set; }
public bool MACD1H { get; set; }
public bool MACD1D { get; set; }
}
public class RootObject
{
public List<Result> results { get; set; }
}

c# json rearrange with same value

How do u make the below json in c#
[
{"file": "fileName1", "key":0, title:"u1"},
{"file": "fileName1", "key":2, title:"u1"},
{"file": "fileName2", "key":5, title:"u1"},
{"file": "fileName2", "key":10, title:"u1"}
]
into this.
{
"fileName1" : [{"key":0, title:"u1"},{"key":2, title:"u1"}],
"fileName2" : [{"key":0, title:"u1"},{"key":2, title:"u1"}]
}
Thank you
I have done a .NEt fiddle for you requirement
https://dotnetfiddle.net/Wsnl9V
using System;
using System.Collections.Generic;
using System.Linq;
using Newtonsoft.Json;
public class Program
{
public static void Main()
{
string input = #"[
{'file': 'fileName1', 'key':0, title:'u1'},
{'file': 'fileName1', 'key':2, title:'u1'},
{'file': 'fileName2', 'key':5, title:'u1'},
{'file': 'fileName2', 'key':10, title:'u1'}
]";
var existingList = JsonConvert.DeserializeObject<List<CurrentType>>(input);
var dictionary = new Dictionary<string,List<RequiredTypeFile>>();
var distinctFileNames = existingList.Select(x=> x.File).Distinct().ToList();
distinctFileNames.ForEach(x=>
{
var fileValue = existingList.Where(m=>m.File==x)
.Select(m => new RequiredTypeFile
{
Key = m.Key,
Title = m.Title
}).ToList();
dictionary.Add(x,fileValue);
});
var reqdJson = JsonConvert.SerializeObject(dictionary);
Console.WriteLine(reqdJson);
}
}
public class CurrentType
{
public string File
{
get;
set;
}
public int Key
{
get;
set;
}
public string Title
{
get;
set;
}
}
public class RequiredTypeFile
{
public int Key
{
get;
set;
}
public string Title
{
get;
set;
}
}

Deserialize JSON List on wp7

I am trying to Deserialize a JSON api to c# on WP7. I need help in doing so. Im sure its an easy fix but i cannot just see it.
The JSON Data looks like this.
{
"chartDate" : 1349564400,
"retrieved" : 1349816722,
"entries" :
[
{
"position" : 1,
"previousPosition" : 0,
"noWeeks" : 1,
"artist" : "Rihanna",
"title" : "Diamonds",
"change" :
{
"direction" : "none",
"amount" : 0,
"actual" : 0
}
},
which translates to the following using http://json2csharp.com/
public class Change
{
public string direction { get; set; }
public int amount { get; set; }
public int actual { get; set; }
}
public class Entry
{
public int position { get; set; }
public int previousPosition { get; set; }
public int noWeeks { get; set; }
public string artist { get; set; }
public string title { get; set; }
public Change change { get; set; }
}
public class RootObject
{
public int chartDate { get; set; }
public int retrieved { get; set; }
public List<Entry> entries { get; set; }
}
In the application when i click the get feed button i am using the following code but it is coming back with the error Cannot Deserilize JSON object into type "System.Collections.Generic.List`1[Appname.RootObject
The following is my C# from Mainpage.cs
using System;
using System.Collections.Generic;
using System.Net;
using System.Windows;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Reactive;
using Newtonsoft.Json;
namespace JsonDemo
{
public partial class MainPage : PhoneApplicationPage
{
// Constructor
public MainPage()
{
InitializeComponent();
}
private void Load_Click(object sender, RoutedEventArgs e)
{
var w = new SharpGIS.GZipWebClient();
Observable.FromEvent<DownloadStringCompletedEventArgs>(w, "DownloadStringCompleted")
.Subscribe(r =>
{
var deserialized = JsonConvert.DeserializeObject<List<RootObject>>(r.EventArgs.Result);
PhoneList.ItemsSource = deserialized;
});
w.DownloadStringAsync(new Uri("http://apiurl.co.uk/labs/json/"));
}
}
}
if r.EventArgs.Result returns the (correct) json in question, this should work:
var deserialized = JsonConvert.DeserializeObject<RootObject>(r.EventArgs.Result);
--EDIT--
string json = #"{
""chartDate"": 1349564400,
""retrieved"": 1349816722,
""entries"": [{
""position"": 1,
""previousPosition"": 0,
""noWeeks"": 1,
""artist"": ""Rihanna"",
""title"": ""Diamonds"",
""change"": {
""direction"": ""none"",
""amount"": 0,
""actual"": 0
}
}]
}";
var deserialized = JsonConvert.DeserializeObject<RootObject>(json);

Categories

Resources