im trying to get a value of JSON with the substring from a config,
using (WebClient wc = new WebClient())
{
string json = wc.DownloadString("****");
dynamic dobj = JsonConvert.DeserializeObject<dynamic>(json);
string kek = dobj[0].ServerSystem.isActive;
if(kek == "True")
{
Console.WriteLine(kek);
Console.ReadLine();
}
else
{
Console.WriteLine(kek);
Console.ReadLine();
}
}
JSON:
[
{
"ServerSystem": {
"isActive": "True",
"Time": "120S"
}
},
{
"License1": {
"Description": "Lorem ipsum dolor gg amet",
"Value": "1"
}
}
]
But i want to get the Value ServerSystem.[FROMCONFIG], but i dont know how to insert it, so i know how to read from a config, but i cant just dO: string kek = dobj[0].ServerSystem + ".BLALBALA";
So how to do it?
Actually your pseudocode nearly got it right.
var keytoget = "Time";
string value dobj[0].ServerSystem[keytoget]
Related
I am trying to search a json file with a string and then return a value from the same object as that string. This is a part of the json file:
[
"7c6b2f",
"EYZ",
"Australia",
1611990353,
1611990419,
144.8364,
-37.6611,
13114.02,
false,
50.42,
171.56,
null,
null,
null,
"5064",
true,
0
],
[
"7c6b0c",
"JST",
"New-Zealand",
1611990440,
1611990440,
148.4636,
-33.7973,
10668,
false,
248.2,
37.84,
-0.33,
null,
11170.92,
"1461",
false,
0
]
I want to have it so that if the user enters EYZ then the code will return Australia. I am currently setting the json file to a string but I am not sure how you would create objects to search in this scenario.
First of all, this is not a valid json file. You need to enclose it in an array element:
[
[
"xyz"
...
],
[
]
]
Once your object is valid, you can you the JSON.Net library to parse it in your code
// Here you'll have your value
string json = #"[
'Small',
'Medium',
'Large'
]";
JArray a = JArray.Parse(json);
And you can see How to access elements of a JArray (or iterate over them) how to iterate/access them.
JSON.Net
public static string Search(string input)
{
using (var sr = new StreamReader("your.json"))
{
var reader = new JsonTextReader(sr);
while (reader.Read())
{
if (reader.TokenType==JsonToken.String)
{
var value = reader.ReadAsString();
if (value == input)
{
return reader.ReadAsString();
}
}
}
}
return null;
}
SystemExtensions.Core
public static string Search(string input)
{
using (var sr = new StreamReader("your.json"))
{
var reader = JsonReader.CreateJson5(sr, 2048);
while (reader.Read())
{
if (reader.IsString)
{
var value = reader.GetString();
if (value == input)
{
if (reader.Read() && reader.IsString)
{
return reader.GetString();
}
}
}
}
}
return null;
}
I know it sounds basic but all answers around this question have been stupidly large and bulky code that does not allow the functionality i need. i need to parse this json array.
[
{
"label":"Cow (1)",
"value":3309
},
{
"label":"Cow (1)",
"value":14998
},
{
"label":"Cow (4)",
"value":20969
},
{
"label":"Cow (4)",
"value":20970
},
{
"label":"Cow (4)",
"value":20971
},
{
"label":"Cowardly Bandit",
"value":1886
},
{
"label":"Cow calf (1)",
"value":2310
},
{
"label":"Coward in armour (82)",
"value":5097
},
{
"label":"Coward with bow (105)",
"value":6049
},
{
"label":"Cow calf (1)",
"value":20979
},
{
"label":"Undead cow (4)",
"value":1691
},
{
"label":"Plague cow",
"value":1998
},
{
"label":"Plague cow",
"value":1999
},
{
"label":"Unicow (57)",
"value":5603
},
{
"label":"Zombie cow (1)",
"value":18597
},
{
"label":"Zombie cow (1)",
"value":20928
},
{
"label":"Super Cow (5)",
"value":21497
},
{
"label":"Dairy cow",
"value":22418
},
{
"label":"Armoured cow thing (62)",
"value":5986
},
{
"label":"Armoured cow thing (62)",
"value":6048
}
]
And when i try to access the data point inside the array it returns null, code:
Stream stream = client.OpenRead("http://services.runescape.com/m=itemdb_rs/bestiary/beastSearch.json?term=" + Input);
StreamReader reader = new StreamReader(stream);
jObject = JObject.Parse(reader.ReadToEnd());
stream.Close();
//put items into list view
// i is the number where the json object is in the array
var lvi = new ListViewItem(new string[] { (string)jObject[i]["label"], (string)jObject[i]["value"] });
I do not want to use classes
Found error in your code. Instead:
JObject.Parse(reader.ReadToEnd());
Write (JObject -> JArray):
string text = reader.ReadToEnd();
var jObject = JArray.Parse(text);
Also when write operation in 2 lines, you will see where the error: in reading from the stream or in serialization.
Not wanting to use classes is weird but not impossible.
var json = reader.ReadToEnd();
var objects = JsonConvert.DeserializeObject<dynamic[]>(json);
var lvi = new ListViewItem(new string[] { (string)objects[i].label, (string)objects[i].value });
Try my answer to this question :
public IEnumerable<MeItem> DeserializeListFromJson(string jsonArray)
{
return JsonConverter.DeserializeObject<List<JObject>>(jsonArray).Select( obj => DeserializeFromJson(obj) );
}
public MeItem DeserializeFromJson(string jsonString)
{
return JsonConvert.DeserializeObject<MeItem>(jsonString);
}
You can find necessary detailed informations in my answer for this question and this one
Edit:
If you do not want to use classes then you can just modify DeserializeFromJson() method into something like this :
public KeyValuePair<string, string> DeserializeFromJson(JObject obj)
{
return new KeyValuePair<string, string>(obj.SelectToken("label").Value<string>(), obj.SelectToken("value").Value<string>());
}
Which will require to modify DeserializeListFromJson() method into :
public IEnumerable<KeyValuePair<string,string>> DeserializeListFromJson(string jsonArray)
{
return JsonConverter.DeserializeObject<List<JObject>>(jsonArray).Select( obj => DeserializeFromJson(obj) );
}
Usage with your case :
Stream stream = client.OpenRead("http://services.runescape.com/m=itemdb_rs/bestiary/beastSearch.json?term=" + Input);
ListViewItem item = null;
using (StreamReader reader = new StreamReader(stream))
{
KeyValuePair<string, string> selected = DeserializeListFromJson(reader.ReadToEnd()).ElementAt(i);
item = new ListViewItem(new string[] { selected.Key, selected.Value });
}
When I get http response it looks like this:
{
"course_editions": {
"2014/SL": [
{
"course_id": "06-DEGZLI0",
"term_id": "2014/SL",
"course_name": {
"en": "Preparation for bachelor exam",
}
},
{
"course_id": "06-DPRALW0",
"term_id": "2014/SL",
"course_name": {
"en": "Work experience",
}
},
{
I would like to be able to extract course title only, f.e.:
Work experience
Preparation for bachelor exam
I've tried this:
string probably_json = GetResponse(url_courses);
object obj = JsonConvert.DeserializeObject(probably_json);
using (StringReader reader = new StringReader(obj.ToString().Replace("\\t", " ").Replace("\\n", "\n")))
{
string line;
int lineNo = 0;
while ((line = reader.ReadLine()) != null)
{
if (line.Contains("en"))
{
string output = line.Substring(0, line.Length-1);
Console.WriteLine(output);
}
++lineNo;
}
} // End Using StreamReader
But that's all I've got:
"en": "Preparation for bachelor exam" "en": "Work experience"
what am I supposed to do, to get course title only ?
If you are using json.net anyways, make it do some work, don't parse yourself:
var result = JObject
.Parse(probably_json)
.SelectTokens("['course_editions'].['2014/SL'].[*].['course_name'].['en']");
I'm trying to write lines in a valid JSON format using C# in a efficient way
What the file should look like:
[
{
"uuid": "c92161ba-7571-3313-9b59-5c615d25251c",
"name": "thijmen321"
},
{
"uuid": "3b90891d-e6fc-44cc-a1a8-e822378ec148",
"name": "TehGTypo"
},
{
"uuid": "5f820c39-5883-4392-b174-3125ac05e38c",
"name": "CaptainSparklez"
}
]
I already have the names and the UUIDs, but I need a way to write them to a file. I want to do this one by one, so, first the file looks like this:
[
{
"uuid": "c92161ba-7571-3313-9b59-5c615d25251c",
"name": "thijmen321"
}
]
Then like this:
[
{
"uuid": "c92161ba-7571-3313-9b59-5c615d25251c",
"name": "thijmen321"
},
{
"uuid": "3b90891d-e6fc-44cc-a1a8-e822378ec148",
"name": "TehGTypo"
}
]
etc. But of course, the UUIDs and the names are different, so how can I do this in a efficient way without using any APIs etc.?
My current (really inefficient) code:
public void addToWhitelist()
{
if (String.IsNullOrEmpty(whitelistAddTextBox.Text)) return;
string player = String.Empty;
try
{
string url = String.Format("https://api.mojang.com/users/profiles/minecraft/{0}", whitelistAddTextBox.Text);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(new Uri(url));
request.Credentials = CredentialCache.DefaultCredentials;
using (WebResponse response = request.GetResponse())
using (StreamReader reader = new StreamReader(response.GetResponseStream()))
player = reader.ReadToEnd();
}
catch (WebException ex)
{
Extensions.ShowError("Cannot connect to http://api.mojang.com/! Check if you have a valid internet connection. Stacktrace: " + ex, MessageBoxIcon.Error);
}
catch (Exception ex)
{
Extensions.ShowError("An error occured! Stacktrace: " + ex, MessageBoxIcon.Error);
}
if (String.IsNullOrWhiteSpace(player)) { Extensions.ShowError("This player doesn't seem to exist.", MessageBoxIcon.Error); return; }
player = player.Replace(",\"legacy\":true", "")
.Replace("\"id", " \"uuid")
.Replace("\"name", " \"name")
.Replace(",", ",\n")
.Replace("{", " {\n")
.Replace("}", "\n },");
File.WriteAllText(Program.programPath + #"\Servers\" + servers[currentIndex].Name + #"\whitelist.json", "");
try
{
using (StreamWriter sw = File.AppendText(Program.programPath + #"\Servers\" + servers[currentIndex].Name + #"\whitelist.json"))
{
sw.WriteLine("[");
foreach (string s in File.ReadAllLines(Program.programPath + #"\Servers\" + servers[currentIndex].Name + #"\whitelist.json"))
if (s.Contains("[") || s.Contains("]") || s.Equals(Environment.NewLine)) continue;
else sw.WriteLine(s);
sw.WriteLine(player);
sw.WriteLine("]");
whitelistListBox.Items.Add("\n" + whitelistAddTextBox.Text);
}
}
catch (Exception ex) { Extensions.ShowError("An error occured while update whitelist.json! Stacktrace: " + ex); }
whitelistAddTextBox.Clear();
}
The recommand "Microsoft" way is with a data contract and the DataContractJsonSerializer.. see here
https://msdn.microsoft.com/de-de/library/system.runtime.serialization.json.datacontractjsonserializer%28v=vs.110%29.aspx
an example of the contact would be:
[DataContract]
internal class Person
{
[DataMember]
internal string name;
[DataMember]
internal string Uuid ;
}
you use the class in the following way (obviously)
Person p = new Person();
p.name = "John";
p.Uuid = "3b90891d-e6fc-44cc-a1a8-e822378ec148";
and serialize it with the Contract Serializer
MemoryStream stream1 = new MemoryStream();
DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(Person));
ser.WriteObject(stream1, p);
example to show the serialzed data:
stream1.Position = 0;
StreamReader sr = new StreamReader(stream1);
Console.WriteLine(sr.ReadToEnd());
Try json.net it will do the serialization job for you: http://www.newtonsoft.com/json
I would use a JSON Serializer like http://www.newtonsoft.com/json
This would allow you to roll your uuid/name as a class, instead of doing the parsing yourself
So something like:
internal class UuidNamePair
{
string Uuid { get; set; }
string Name { get; set; }
}
Then when calling this, you would just do something like this:
List<UuidNamePair> lst = new List<UuidNamePair>();
lst.Add(new UuidNamePair() { Name = "thijmen321", Uuid = "c92161ba-7571-3313-9b59-5c615d25251c" });
lst.Add(new UuidNamePair() { Name = "TehGTypo", Uuid = "3b90891d-e6fc-44cc-a1a8-e822378ec148" });
string json = JsonConvert.SerializeObject(lst, Formatting.Indented);
Console.WriteLine(json);
Instead of the Console.WriteLine, you could do your POST to a web service or however you're trying to use this json.
I have pass the JSON value as String & in C# need to convert to DataTable.
I have done in android part,(making a json as String)
public void getUploadTableData(){
DBAdapter dbAdapter = DBAdapter.getDBAdapterInstance(this);
dbAdapter.openDataBase();
try {
if(uploadTable.size() > 0){
for (Map.Entry<Integer, String> entry : uploadTable.entrySet()) {
int key = entry.getKey();
String value = entry.getValue();
JSONObject invHeader = new JSONObject();
if(value.equals("WMInvoiceHeader")){
String query = "SELECT BusinessUnit,ExecutiveCode,InvoiceNo,SalesCategory,RetailerCode," +
" RetailerCodeSon,InvoiceDate,GrossValue,InvoiceValue,TotalLineDiscount," +
" FROM WMInvoiceHeader " +
" WHERE (CancelFlag IS NULL OR CancelFlag ='0')";
ArrayList<?> stringList = dbAdapter.selectRecordsFromDBList(query, null);
if(stringList.size() > 0){
for (int i = 0; i < stringList.size(); i++) {
ArrayList<?> arrayList = (ArrayList<?>) stringList.get(i);
ArrayList<?> list = arrayList;
invHeader.put("BusinessUnit",(String)list.get(0));
invHeader.put("ExecutiveCode",(String)list.get(1));
invHeader.put("InvoiceNo",(String)list.get(2));
invHeader.put("SalesCategory",(String)list.get(3));
invHeader.put("RetailerCode",(String)list.get(4));
invHeader.put("RetailerCodeSon",(String)list.get(5));
invHeader.put("InvoiceDate",(String)list.get(6));
invHeader.put("GrossValue",(String)list.get(7));
invHeader.put("InvoiceValue",(String)list.get(8));
invHeader.put("TotalLineDiscount",(String)list.get(9));
}
System.out.println("----invHeader---" + invHeader.toString());
}
soapPrimitiveData("WMInvoiceHeader", strBusinessUnit, strExecutive, invHeader.toString());
}
// System.out.println("----invHeader---" + invHeader.toString());
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
This is my webservice part....
// ksoap2 calling wcf
public SoapPrimitive soapPrimitiveData(String tablename,String strBusinessUnit, String strExecutive,String jsonString) throws IOException,XmlPullParserException {
SoapPrimitive responsesData = null;
SoapObject requestData = new SoapObject(NAMESPACE, METHOD_NAME); // set
requestData.addProperty("strBusinessUnit", strBusinessUnit);
requestData.addProperty("strExecutive", strExecutive);
requestData.addProperty("strTableName", tablename);
requestData.addProperty("jsonContent", jsonString);
SoapSerializationEnvelope envelopes = new SoapSerializationEnvelope(SoapEnvelope.VER11); // put all required data into a soap//// envelope
envelopes.dotNet = true;
envelopes.setOutputSoapObject(requestData);
AndroidHttpTransport httpTransport = new AndroidHttpTransport(APPURL);
httpTransport.debug = true;
try {
httpTransport.call(SOAP_ACTION, envelopes);
responsesData = (SoapPrimitive) envelopes.getResponse();
} catch (SocketException ex) {
Log.e("Error : " , "Error on soapPrimitiveData() " + ex.getMessage());
ex.printStackTrace();
} catch (Exception e) {
Log.e("Error : " , "Error on soapPrimitiveData() " + e.getMessage());
e.printStackTrace();
}
return responsesData;
}
This is my C# code
public bool convertJSONToDataSet(string strBusinessUnit, string strExecutiveCode, string strTableName, string jsonContent)
{
bool status =false;
DataTable dataTable = JsonConvert.DeserializeObject<DataTable>(jsonContent);
status = UpdateUploadData(strBusinessUnit, strExecutiveCode, strTableName, dataTable);
return status;
}
When i call webservice this method conversion part giving error .It say Additional text found in JSON string after finishing deserializing object.
This is my json result in C#
{
"SpecialDiscountFlag": "0",
"TotalLineDiscount": "0",
"ExecutiveCode": "TEST001",
"InvoiceValue": "3000",
"InvoiceDate": "2011-11-17",
"RouteCode": "VRT002",
"RetailerCode": "TEST0007",
"HeaderDiscountFlag": "1",
"GrossValue": "3000",
"UploadedOn": "2011-11-17",
"SalesType": "O",
"VisitNumber": "26",
"UploadFlag": "1",
"InvoiceNo": "26",
"SalesCategory": "VSAO",
"BusinessUnit": "MASS",
"VisitSequence": "1",
"UploadedBy": "TEST001",
"TotalHeaderDiscount": "0"
}
Please tell me what is wrong here.
I want to do the Convert JSON as String to DataTable in C#
Json string should be like below:
{
"List": [
{
"ProjectId": 504,
"RowId": 1,
"ProjectName": "Google",
"Member": "Private"
},
{
"ProjectId": 503,
"RowId": 2,
"ProjectName": "Facebook",
"Member": "Public"
}
]
}
Where "List" treated as your table name and data inside curly brackets treated as row for DataTable
To validate json string you can use this site: http://jsonlint.com/