I've been reading for hours and still can't figure out how to use this
under my button I have
WebClient wc = new WebClient();
Uri uri = new Uri("url");
string json = wc.DownloadString(uri);
var a = JsonConvert.DeserializeObject<RootObject>(json);
and the classes
public class Shares
{
public int valid { get; set; }
public int invalid { get; set; }
public int id { get; set; }
public int donate_percent { get; set; }
public int is_anonymous { get; set; }
public string username { get; set; }
}
public class Transactions
{
public double Credit { get; set; }
public double Debit_MP { get; set; }
public double Fee { get; set; }
public int TXFee { get; set; }
}
public class Data
{
public string username { get; set; }
public Shares shares { get; set; }
public int hashrate { get; set; }
public string sharerate { get; set; }
public Transactions transactions { get; set; }
}
public class Getuserstatus
{
public string version { get; set; }
public double runtime { get; set; }
public Data data { get; set; }
}
public class RootObject
{
public Getuserstatus getuserstatus { get; set; }
}
I did a messagebox to check the string from the URL and all the data is there but it doesn't put it into the fields when I call them they're all empty
Shares Share = new Shares();
textBox1.Text += "Username: " + Share.username;
edit:
ok I got it working the a.getsuerstatus.data.shares.username is not valid in the api I don't know why jsontocsharp site added it but all the data is there username is actually a.getuserstatus.data.username thank you all for the help or I would have still be trying to call data using Shares Share = new Shares()
The following code:
Shares Share = new Shares();
textBox1.Text += "Username: " + Share.username;
creates a new instance of an object of type Shares which has the username property initialized to an empty string.
There is no connection with the json-formatted text you'd like to parse.
The method that you are using to parse the json string: var a = JsonConvert.DeserializeObject<RootObject>(json); expects to generate an object of type RootObject
You will want to set the Text property of textbox1 equal to the corresponding Shares object that is deserialized into a.
textbox1.Text = a.getUserStatus.data.shares.username;
The problem isn't the deserialization, it's this;
Shares Share = new Shares();
textBox1.Text += "Username: " + Share.username;
which instead needs to be
textBox1.Text += "Username: " + a.getUserStatus.data.username;
a is the object instantiated by json.NET. You need to go through all the indirection to access the value of username, not just allocated a new Share instance and access it's username, the two references point to entirely different objects.
Related
Hey all I am trying to figure out how to go about saving just one value in my JSON class instead of having to write the whole JSON out again with "New". I am using the Newton JSON.Net.
This is my JSON structure:
public class GV
{
public class Data
{
[JsonProperty("pathForNESPosters")]
public static string PathForNESPosters { get; set; }
[JsonProperty("pathForSNESPosters")]
public static string PathForSNESPosters { get; set; }
[JsonProperty("pathForSEGAPosters")]
public static string PathForSEGAPosters { get; set; }
[JsonProperty("pathToNESContent")]
public static string PathToNESContent { get; set; }
[JsonProperty("pathToSNESContent")]
public static string PathToSNESContent { get; set; }
[JsonProperty("pathToSEGAContent")]
public static string PathToSEGAContent { get; set; }
[JsonProperty("lastSavedVolume")]
public static double LastSavedVolume { get; set; }
}
public class Root
{
public Data data { get; set; }
}
And I have no issues with loading that data from a file into my class:
GV.Root myDeserializedClass = JsonConvert.DeserializeObject<GV.Root>(File.ReadAllText(
currentAssemblyPath + String.Format(#"\Resources\{0}", "dataForLinks.json")
));
But I have yet to find anything searching that will let me do one update to an object in the class without wiping it out doing a New statement.
What I am wanting to do is something like the following:
-Load the json into my class object [Done]
-Save a value thats in my class object [stuck here]
GV.pathToNESContent = "new value here";
-Save class object (with the one new value) back to the file for which it came from preserving the other original values. [not here yet]
When I update just that one class object I am wanting to contain the original values for all the other JSON data I read in from the file.
Anyone have a good example of the above you can share?
update
I'd ditch the inner class structure:
namespace GV
{
public class Data
{
[JsonProperty("pathForNESPosters")]
public string PathForNESPosters { get; set; }
[JsonProperty("pathForSNESPosters")]
public string PathForSNESPosters { get; set; }
[JsonProperty("pathForSEGAPosters")]
public string PathForSEGAPosters { get; set; }
[JsonProperty("pathToNESContent")]
public string PathToNESContent { get; set; }
[JsonProperty("pathToSNESContent")]
public string PathToSNESContent { get; set; }
[JsonProperty("pathToSEGAContent")]
public string PathToSEGAContent { get; set; }
[JsonProperty("lastSavedVolume")]
public double LastSavedVolume { get; set; }
}
public class Root
{
public Data Data { get; set; }
}
Deser (use Path.Combine to build paths, not string concat):
var x = JsonConvert.DeserializeObject<GV.Root>(File.ReadAllText(
Path.Combine(currentAssemblyPath, "Resources", "dataForLinks.json"))
));
Edit:
x.Data.PathToNESContent = "...";
and re-ser
I am having trouble in converting some string to JSON.
I use C# WebAPI to Deserialize string
First: List<GetBookInfoModel> list = JsonConvert.DeserializeObject<List<GetBookInfoModel>>(strOutput01);
Second:List <GetBookDetInfoModel> list = JsonConvert.DeserializeObject<List<GetBookDetInfoModel>>(strOutput01);
And my Json String is like:
First: [{"allbook ":{ " count01 " :3}, " late ":{ " count02 ":0}}]
Second: [{"num ":1, " bookname ":"AAAAA","FinTime ":"2017"},{"num ":2, " bookname ":"iOS","FinTime ":"2017"},{"num ":3, " bookname ":"Visual","FinTime ":"2017"}]
And my Model class is like..
public class GetBookInfoModel
{
List<GetBookSecondInfoModel> allbook { get; set; }
List<GetBookSecondInfoModel> late { get; set; }
}
public class GetBookSecondInfoModel
{
public string count01 { get; set; }
public string count02 { get; set; }
}
public class GetBookDetInfoModel
{
public string num { get; set; }
public string bookname { get; set; }
public string FinTime { get; set; }
}
But now it returns null.
How can I resolve this problem?Thanks.
It turns out there are 3 issues for the former.
1) The properties of GetBookInfoModel should be public.
public class GetBookInfoModel
{
public List<GetBookSecondInfoModel> allbook { get; set; }
public List<GetBookSecondInfoModel> late { get; set; }
}
2) The unnecessary spaces between paired quotes in JSON should be removed.
3) Both allbook and late in JSON should be followed by [].
[{"allbook":[{ "count01" :3}], "late":[{ "count02":0}]}]
Similar for the latter.
I have a response from Jira API, require to be deserialized into data model:
com.atlassian.greenhopper.service.sprint.Sprint#40675167[id=10151,rapidViewId=171,state=CLOSED,name=Sprint 37.1,startDate=2015-07-30T16:00:22.000+03:00,endDate=2015-08-13T16:00:00.000+03:00,completeDate=2015-08-13T14:31:34.343+03:00,sequence=10151]
This is actually the information of current sprint for issue.
I need to deserialize it to a model like:
public class Model
{
public string name { get; set; }
...
}
I have already removed all non-required information, like com.atlassian.greenhopper.service.sprint.Sprint#40675167 using Regex pattern \[(.*?)\] so I have brackets and all inside.
Now I stopped completely trying to find the a way to convert this string to a data model.
Found the following thread at the Atlassian Answers page and there appears to be no JSON representation of that inner Object. As shown in the example from that thread:
customfield_10007:[
"com.atlassian.greenhopper.service.sprint.Sprint#a29f07[rapidViewId=<null>,state=CLOSED,name=NORD - Sprint 42,startDate=2013-07-29T06:47:00.000+02:00,endDate=2013-08-11T20:47:00.000+02:00,completeDate=2013-08-14T15:31:33.157+02:00,id=107]",
"com.atlassian.greenhopper.service.sprint.Sprint#769133[rapidViewId=<null>,state=ACTIVE,name=NORD - Sprint 43,startDate=2013-08-14T15:32:47.322+02:00,endDate=2013-08-23T15:32:47.322+02:00,completeDate=<null>,id=117]"
],
The response is indeed a JSON array, but the array itself contains CSV's, so you can make use of the following to parse that:
public class DataObject
{
public string id { get; set; }
public string rapidViewId { get; set; }
public string state { get; set; }
public string name { get; set; }
public string startDate { get; set; }
public string endDate { get; set; }
public string completeDate { get; set; }
public string sequence { get; set; }
}
public class Program
{
private const string sampleStringData =
#"[id=10151,rapidViewId=171,state=CLOSED,name=Sprint 37.1,startDate=2015-07-30T16:00:22.000+03:00,endDate=2015-08-13T16:00:00.000+03:00,completeDate=2015-08-13T14:31:34.343+03:00,sequence=10151]";
static void Main(string[] args)
{
var dataObject = new DataObject();
string[][] splitted;
var sampleWithNoBrackets = sampleStringData.Substring(1,sampleStringData.Length-2);
splitted = sampleWithNoBrackets.Split(',').Select(p => p.Split('=')).ToArray();
dataObject.id = splitted[0][1];
dataObject.rapidViewId = splitted[1][1];
dataObject.state = splitted[2][1];
dataObject.name = splitted[3][1];
dataObject.startDate = splitted[4][1];
dataObject.endDate = splitted[5][1];
dataObject.completeDate = splitted[6][1];
dataObject.sequence = splitted[7][1];
Console.ReadKey();
}
}
Here's the output for the above:
i have json string as
{"AccountNo":"345234533466","AuthValue":"{\"TopUpMobileNumber\":\"345234533466\",\"VoucherAmount\":\"100\"}"}
to parse this string i have created class as
public class UserContext
{
public string AccountNo { get; set; }
public string AuthValue { get; set; }
}
in AuthValue it gives me output as {\"TopUpMobileNumber\":\"345234533466\",\"VoucherAmount\":\"100\"} which is absolutely correct. now i want to modify my class in such way that i want AuthValue in string format as well and in seprate member variable format.
so i modify my class in this way but it gives error
public class UserContext
{
public string AccountNo { get; set; }
public string AuthValue { get; set; }
public Auth ????? { get; set; }
}
public class Auth
{
public string TopUpMobileNumber { get; set; }
public string VoucherAmount { get; set; }
}
My requirement is
AuthValue whole json string i required
in another variable i want member wise values
Parsing Logic
UserContext conObj1 = new UserContext();
conObj1 = JsonConvert.DeserializeObject<UserContext>(context);
Note : No modification in json string is allowed.
I'm not very familiar with JsonConvert or Json.NET so I'm not sure what options are available for that. Personally I'd just call the deserializer again immediately afterwards.
UserContext conObj1 = new UserContext();
conObj1 = JsonConvert.DeserializeObject<UserContext>(context);
conObj1.AuthObject = JsonConvert.DeserializeObject<Auth>(conObj1.AuthValue);
You could move this into the class if you wanted and call it directly off the deserialized class.
public class UserContext
{
public string AccountNo { get; set; }
public string AuthValue { get; set; }
public Auth AuthObject { get; private set; }
internal UserContext Deserialize()
{
// Serialize the object
this.AuthObject = JsonConvert.DeserializeObject<Auth>(this.AuthValue);
// Return this object for a simple single-line call.
return this;
}
}
// Single object
UserContext conObj1 = new UserContext();
conObj1 = JsonConvert.DeserializeObject<UserContext>(context).Deserialize();
// Enumeration of object (given that this is supported in JsonConvert)
IEnumerable<UserContext> conObjs = JsonConvert.DeserializeObject<IEnumerable<UserContext>(contexts).Select(c => c.Deserialize()).ToList();
Or if you feel self hating you could go as far as doing the deserialization at the time the property is accessed (although I would avoid this at almost all costs due to the numerous issues it can cause).
public class UserContext
{
private Auth m_auth;
public string AccountNo { get; set; }
public string AuthValue { get; set; }
public Auth AuthObject
{
get
{
if (this.m_auth == null)
{
this.m_auth = JsonConvert.DeserializeObject<Auth>(this.AuthValue);
}
return this.m_auth;
}
}
}
I would suggest using two classes - one for the JSON you're actually receiving, and then one for the object model you want to use:
public class JsonUserContext
{
public string AccountNo { get; set; }
public string AuthValue { get; set; }
}
public class UserContext
{
public string AccountNo { get; set; }
public Auth AuthValue { get; set; }
}
public class Auth
{
public string TopUpMobileNumber { get; set; }
public string VoucherAmount { get; set; }
}
...
var jsonUserContext = JsonConvert.DeserializeObject<JsonUserContext>(json);
var authJson = jsonUserContext.AuthValue;
var userContext = new UserContext {
AccountNo = jsonUserContext.AccountNo,
AuthValue = JsonConvert.DeserializeObject<JsonUserContext>(authJson);
};
I have an application that will parse an excel file and add a column, then generate a new CSV file with the results. I am able to create a list of the items I want in the file, but I cannot figure out how to pass that list to the method that is generating the new file.
I have the following class:
public class LocationData
{
public string PostalCode { get; set; }
public string Partner { get; set; }
public string LocationID { get; set; }
public string Name { get; set; }
public string Country { get; set; }
public string Market { get; set; }
}
and the following code to get the data into a list:
LocationData Locationdata = new LocationData()
{
PostalCode = location[0],
Partner = location[1],
LocationID = location[2],
Name = location[3],
Country = location[4],
Market = repository.GetMarketsForPostalCode(location[0])
}
I also have the method to create the csv and I need to pass in the list info, but I get the error:
foreach statement cannot operate on variables of type 'app.LocationData' because 'app.LocationData' does not contain a public definition for 'GetEnumerator'
I think you are misunderstanding what a list is in C#. I think you need the List data type. Try this:
List<string> Locationdata = new List<string>()
{
location[0],
location[1],
location[2],
location[3],
location[4],
repository.GetMarketsForPostalCode(location[0])
};
Your csv function will look like this
public void GenerateCSV(List<LocationData> data)
{
foreach (LocationData d in data)
{
//put line in csv as
string s = d.PostalCode + "," d.Partner + _"," + d.LocationID...... + Environment.NewLine;
}
}
Your class declaration will remain same
public class LocationData
{
public string PostalCode { get; set; }
public string Partner { get; set; }
public string LocationID { get; set; }
public string Name { get; set; }
public string Country { get; set; }
public string Market { get; set; }
}
Now you need to add all the data in the list first
which you will do like this
List<LocationData> lst = new List<LocationData>();
LocationData ld = new LocationData();
ld.LocationID = "0";
ld.Market = "market";
lst.Add(ld);
........
GenerateCSV(lst);