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/
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();
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'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 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\",");
Android application transfer data from android sqlite database to sql server db through the service. This is working fine. Problem is double type value , it convert to integer (not for all only GPS- location coordinate ).
This is my code :
JSONArray jaVisitDetail= new JSONArray();
StringBuffer visitDetail = new StringBuffer();
visitDetail.append("{\"WMVisitDetail\":");
for (int i = 0; i < stringList.size(); i++) {
ArrayList<?> arrayList = (ArrayList<?>) stringList.get(i);
ArrayList<?> list = arrayList;
if(((String) list.get(20)) != null && !((String) list.get(20)).equals("")) {
//DecimalFormat df = new DecimalFormat("#0.0000");
visitDe.put("Latitude",Double.parseDouble((String)list.get(20)));
//visitDe.put("Latitude",df.format(Double.parseDouble((String)list.get(20))));
//visitDe.put("Latitude",(String)list.get(20));
}else {
visitDe.put("Latitude",0.0000);
}
if(((String) list.get(21)) != null && !((String) list.get(21)).equals("")) {
//DecimalFormat df = new DecimalFormat("#0.0000");
visitDe.put("Longitude",Double.parseDouble((String)list.get(21)));
//visitDe.put("Longitude",df.format(Double.parseDouble((String)list.get(21))));
//visitDe.put("Longitude",(String)list.get(21));
}else {
visitDe.put("Longitude",0.0000);
}
jaVisitDetail.put(visitDe);
}
visitDetail.append(jaVisitDetail.toString());
visitDetail.append("}");
This isC# code :
public bool convertJSONToDataSet(string strBusinessUnit, string strExecutiveCode, string strTableName, string jsonContent)
{
bool status =false;
try
{
DataSet ds = JsonConvert.DeserializeObject<DataSet>(jsonContent);
DataTable dt = ds.Tables[0];
status = UpdateUploadData(strBusinessUnit, strExecutiveCode, strTableName, dt);
}
catch (FaultException err)
{
status = false;
}
catch (Exception error)
{
string gg = error.Message;
Console.WriteLine(gg);
status = false;
}
return status;
}
If we send the Longitude /latitude as double then DeserializeObjecttake this as integer
If we send the Longitude /latitude as string then error is :
`Input string was not in a correct format.Couldn't store <6.9292> in Latitude Column. Expected type is Int64.`
This is set of json data
{
"ExecutiveCode":"EXEC03",
"ReasonCode":" ",
"SurveyNumber":" ",
"RetailerCode":"2975",
"UploadedType":" ",
"CallStartTime":"09:11:58",
"ActualValue":"30600",
"UploadedOn":" ",
"Status":"1",
"MTDAcheivedValue":0,
"ActiveStatus":"1",
"UploadFlag":"1",
"VisitNumber":"83",
"BusinessUnit":"MASS",
"UploadedMethod":" ",
"RetailerCodeSon":"",
"Latitude":"6.9294",
"VisitSequence":"58",
"Longitude":"79.9038",
"RetailerType":" ",
"UploadedBy":" ",
"CallEndTime":"09:14:41"
}
How can we sort of this issue?