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.
Related
I have created a Windows Form Application Function to validate an Api. But the code is breaking ar Deserialize Line. I need to check for Status . If Status=1 is stored in StatusCode string. I can proceed ahead. Please assist.
Function Code :
private void Validate_CW_Account(string Company_Code , string Username , string Password)
{
try
{
string sURL = "";
string baseURL = "https://www.compelapps.in/efacilito_UAT_Api/api/CocktailWorld/Validate_CW_Account_Migration?";
sURL = baseURL+ "StrCompanyCode=" + Company_Code + "&StrUsername=" + Username + "&StrPassword=" + Password;
var client = new RestClient(sURL);
client.Timeout = -1;
var request = new RestRequest(Method.GET);
request.AddHeader("Content-Type", "application/json");
request.AddParameter("application/json", sURL, ParameterType.QueryString);
IRestResponse response = client.Execute(request);
Console.WriteLine(response.Content);
string json_response = response.Content.ToString();
CW_API_Response cw = JsonConvert.DeserializeObject<CW_API_Response>(json_response);
string StatusCode = cw.Status;
if (StatusCode == "1")
{
lbl_AccountConn_Status.Text = "SUCCESSFUL";
lbl_AccountConn_Status.BackColor = System.Drawing.Color.GreenYellow;
lbl_AccountConn_Status.ForeColor = System.Drawing.Color.Black;
}
else
{
lbl_AccountConn_Status.Text = "AUTHENTICATION FAILED";
lbl_AccountConn_Status.BackColor = System.Drawing.Color.Red;
lbl_AccountConn_Status.ForeColor = System.Drawing.Color.White;
}
}
catch (Exception ex)
{
throw ex;
}
}
Class File Code :
public class CW_API_Response
{
public string Status { get; set; }
public string Company_ID { get; set; }
}
If the JSON returned by API is [ { "Company_ID": 11, "Status": 1 } ] then you need to read JSON List. You are not reading list. You are assuming single value.
Try this:
List<CW_API_Response> cw = JsonConvert.DeserializeObject<List<CW_API_Response>>(json_response);
string StatusCode = cw[0].Status.ToString();
Can anyone help me with the correct notation of receiving a JSON POST request in PHP and a working (and aligned) C Sharp script for sending the POST request. I want a decentral login on my PC (with C Sharp software) which uses a JSON POST request to connect to my MySQL database (through a PHP 7.1.1 plugin) on my webspace. I can see the Exceptions (so the JSON feedback is received properly) which the script returns but the PHP POST superglobal keeps coming up empty (on the request side).
My C Sharp script:
using Newtonsoft.Json;
using System;
using System.IO;
using System.Net;
using System.Windows.Forms;
namespace HBI_Statistics_UI
{
public partial class Login : Form
{
public class API_Response
{
public bool IsError { get; set; }
public string ErrorMessage { get; set; }
public string ResponseData { get; set; }
}
public Login()
{
InitializeComponent();
}
private void buttonLogin_Click(object sender, EventArgs e)
{
try
{
// request params
var apiUrl = "http://www.home-business-intelligence.net/plugin/HBI-Statistics/login.php";
var httpWebRequest = (HttpWebRequest)WebRequest.Create(apiUrl);
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST";
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
string json = "json=" + "{\"Email\":\"" + textBox1.Text + "\"," +
"\"Pwd\":\"" + textBox2.Text + "\"}";
streamWriter.Write(json);
streamWriter.Flush();
streamWriter.Close();
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
API_Response r = JsonConvert.DeserializeObject<API_Response>(result);
// check response
if (r.ResponseData == "Success")
{
this.Hide();
ProgramMainUI pr = new ProgramMainUI();
pr.Show();
}
else
{
MessageBox.Show(r.ErrorMessage, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
catch (System.Net.WebException ex)
{
MessageBox.Show(ex.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
catch (Newtonsoft.Json.JsonReaderException ne)
{
MessageBox.Show(ne.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
My PHP Script:
include ("library.php");
try
{
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
// Post Request
$api_data = strip_tags(isset($_POST['json']) ? $_POST['json'] : '');
// Validate Request
if (empty($api_data))
{
throw new Exception('Invalid request!! Please provide login details.' . print_r($api_data));
}
if (!empty($api_data))
{
// Decode json
$data = json_decode($api_data, true);
// Set connection
$conn = Connection::Conn_2();
// Sanitize data for query
$pwd = mysqli_real_escape_string($conn, $data->json->Pwd);
$email = mysqli_real_escape_string($conn, $data->json->Email);
$pwd2 = VanillaSpecial::Hash($pwd); // Hashed Password
// Insert Query of SQL
$result = mysqli_query($conn, $sql = "SELECT * FROM `Management-employees` WHERE email='$email' AND password = '$pwd2'") or die(json_encode(array(
'IsError' => 'true',
'ErrorMessage' => 'Invalid Request!! Oops, something went wrong. Please try again!!'
)));
if (mysqli_num_rows($result) == 1)
{
// output data of each row
while ($row = mysqli_fetch_assoc($result))
{
$functionCategory = $row[functionCategoryID];
}
switch ($functionCategory)
{
case "Management":
// echo "You have got clearance for this page!";
exit(json_encode(array(
'IsError' => 'false',
'ResponseData' => 'Success'
)));
break;
default:
throw new Exception('Invalid clearance!!');
}
}
else
{
throw new Exception('ERROR: Could not be able to execute ' . $sql . ' - ' . mysqli_error($conn));
}
}
}
else
{
throw new Exception('Invalid access method!!');
}
}
catch(Exception $e)
{
exit(json_encode(array(
'IsError' => 'true',
'ErrorMessage' => $e->getMessage()
)));
}
using (var client = new HttpClient())
{
var values = new Dictionary<string, string>
{
{ "thing1", "hello" },
{ "thing2", "world" }
};
var content = new FormUrlEncodedContent(values);
var response = await client.PostAsync("http://www.example.com/recepticle.aspx", content);
var responseString = await response.Content.ReadAsStringAsync();
}
I have an JSON object that looks like this:
"field2_body":null,"field3_body":null,"field4_body":null,"h_phrases":[{"h_phrase":"H222"},{"h_phrase":"H411"},{"h_phrase":"H361"},{"h_phrase":"H315"}]
But this is only a part of the JSON object because it is very big.
What I want to do is to access the h_phrase string values but when i try i get this error:
ERROR Unexpected character encountered while parsing value: {. Path '[0].h_phrases', line 64, position 7.
And this is my code:
public class PhrasesData
{
[JsonProperty(PropertyName = "h_phrases")]
public string H_Phrases { get; set; }
}
public async void getPhrasesForSpecificProduct(string productId)
{
var baseUrl = "http://www.kemtest.com/rest/organisations";
var specProductUrl = baseUrl + "/" + activeOrganisationId + "/" + "products/" + productId;
try
{
var baseAddress = new Uri(specProductUrl);
var cookieContainer = new CookieContainer();
using (var handler = new HttpClientHandler() { CookieContainer = cookieContainer })
using (var client = new HttpClient(handler) { BaseAddress = baseAddress })
{
validToken = System.Net.WebUtility.UrlEncode(validToken);
cookieContainer.Add(baseAddress, new Cookie("access_token", string.Format(validToken)));
var result = client.GetAsync(specProductUrl).Result;
result.EnsureSuccessStatusCode();
if (result.IsSuccessStatusCode)
{
var content = await result.Content.ReadAsStringAsync();
var array = JArray.Parse(content);
PhrasesData[] myPhrasesData = JsonConvert.DeserializeObject<PhrasesData[]>(array.ToString());
if (myPhrasesData == null)
throw new JsonException();
string[] H_PhrasesArr = new string[myPhrasesData.Length];
for (int i = 0; i < myPhrasesData.Length; i++)
{
H_PhrasesArr[i] = myPhrasesData[i].H_Phrases;
var H_PhrasesVar = H_PhrasesArr[i];
Debug.WriteLine("God Damn PHRASES: " + H_PhrasesVar);
}
}
}
}catch (Exception ex) { Debug.WriteLine(#" ERROR {0}", ex.Message); }
}
What's the problem with my code?
Your JSON string is invalid. You need to enclose it with { and }.
Use http://jsonlint.com/ before coding with JSON objects.
{
"field2_body": null,
"field3_body": null,
"field4_body": null,
"h_phrases": [{
"h_phrase": "H222"
}, {
"h_phrase": "H411"
}, {
"h_phrase": "H361"
}, {
"h_phrase": "H315"
}]
}
i am trying to detect what language the written txt of player.LastChat is, and i am having some difficulties.
Here's the code i have:
String[] words = player.LastChat.Trim().Split(new Char[]{' ','\t',',','.',':','!','?',';','(',')',']','[','"'});
StringBuilder edited = new StringBuilder();
// Remove exception list words from line
foreach (String w in words) {
if (plugin.isInList(w, "good_words")) {
continue;
}
edited.Append(w);
edited.Append(" ");
}
// URL Encode edited string
String UnreservedChars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_.~";
StringBuilder Result = new StringBuilder();
String Input = edited.ToString();
for (int x = 0; x < Input.Length; ++x)
{
if (UnreservedChars.IndexOf(Input[x]) != -1)
Result.Append(Input[x]);
else
Result.Append("%").Append(String.Format("{0:X2}", (int)Input[x]));
}
String key = "API KEY";
// Test for badness
bool jsonresult = false;
try {
WebClient client = new WebClient();
String json = client.DownloadString("https://www.googleapis.com/language/translate/v2/detect?key=" + key + "&q=" + Result.ToString());
jsonresult = json.Contains("en");
} catch (Exception e) {
plugin.ConsoleWrite("Language check failed! Error: " + e);
}
if (!jsonresult) {
return true;
}
plugin.ConsoleWrite("Language: " + jsonresult);
return jsonresult; // for Actions
So, what i am trying to achieve, is to return true if it is any other language than "en" (english), but it is returning true no matter what.
The response from google is this:
{
"data": {
"detections": [
[
{
"language": "en",
"isReliable": false,
"confidence": 0.03396887
}
]
]
}
}
Any help is much appreciated, and i have no idea how to code, this code is borrowed from another script.
Regards.
To make method work as described, you should change:
if (!jsonresult) {
return true;
}
plugin.ConsoleWrite("Language: " + jsonresult);
return jsonresult;
to:
plugin.ConsoleWrite("Language: " + jsonresult);
return !jsonresult;
also this line
jsonresult = json.Contains("en");
is checking for any occurance of "en" in json text (and is found in "confidence" in your json). What you should do, is to parse Json using json.net (or other lib), or simply do this (but is an ugly hack):
jsonresult = json.Contains("\"language\": \"en\",");
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/