I want to remove backslash from json result
current result like this:
"{\"Info\":[{\"Full_Eng_Nmae\":\"anda norse\",\"email\":\"keer0#gm
my code is like this
public string GetDetails(string OrderID)
{
OrderContract order = new OrderContract();
DataSet dataSet = new DataSet();
try
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString1"].ConnectionString);
con.Close();
con.Open();
SqlDataAdapter da = new SqlDataAdapter("select Full_Eng_Nmae,email,mobile,client_id from Students where Center_id='" + OrderID + "'", con);
da.Fill(dataSet,"Info");
dataSet.AcceptChanges();
string json = JsonConvert.SerializeObject(dataSet);
return json;
}
catch (Exception ex)
{
throw new FaultException<string>
(ex.Message);
}
}
any one can help me plz?
Thanks
also this full of my code
my Interface:
[ServiceContract]
public interface IOrderService
{
[OperationContract]
[WebGet(UriTemplate = "/GetOrderDetails/{OrderID}",
RequestFormat = WebMessageFormat.Json,
ResponseFormat = WebMessageFormat.Json)]
string GetOrderDetails(string OrderID);
}
I bet there is no backslash, but the printing code that you are using is adding them.
Related
I'm trying to create an api endpoint that returns an element by id , but JsonResult makes an array from DataTable which is supposed to have only one object
[HttpGet("{id:int}")]
public JsonResult GetUser(int id)
{
string query = #"select id,number,name,lastName from dbo.Users where id=" + id;
DataTable table = new DataTable();
string sqlDataSource = _configuration.GetConnectionString("UsersDb");
SqlDataReader myreader;
using (SqlConnection myCon = new SqlConnection(sqlDataSource))
{
myCon.Open();
using (SqlCommand myComm = new SqlCommand(query, myCon))
{
myreader = myComm.ExecuteReader();
table.Load(myreader);
myreader.Close();
myCon.Close();
}
}
return new JsonResult(table);
}
However i get this result with squared brackets on the sides
[{"id":4,"number":10,"name":"Peter","lastName":"Peterson"}]
try this
return new JsonResult(JArray.FromObject(dt).First())
result
{"id":4,"number":10,"name":"Peter","lastName":"Peterson"}
You can just return table.Rows[0] rather than the whole table.
There are other improvements here:
Parameterize your query. Do not inject data into your SQL.
Missing using on the reader.
Consider making this function async
[HttpGet("{id:int}")]
public JsonResult GetUser(int id)
{
const string query = #"#
select
id,
number,
name,
lastName
from dbo.Users
where id = #id;
";
DataTable table = new DataTable();
string sqlDataSource = _configuration.GetConnectionString("UsersDb");
using (SqlConnection myCon = new SqlConnection(sqlDataSource))
using (SqlCommand myComm = new SqlCommand(query, myCon))
{
myComm.Parameters.Add("#id", SqlDbType.Int).Value = id;
myCon.Open();
using(var myreader = myComm.ExecuteReader())
{
table.Load(myreader);
}
}
return new JsonResult(table.Rows[0]);
}
I want remove first and Last place og double Quote in JSON,
public interface ITFSService
{
[OperationContract]
[WebInvoke(Method = "GET", UriTemplate = "TFS_GetProject", ResponseFormat = WebMessageFormat.Json)]
string TFS_GetProject();
}
and my return methods is
public string TFS_GetProject()
{
String json = String.Empty;
try
{
DataTable dtbl = new DataTable();
SqlDataAdapter da = new SqlDataAdapter("SELECT ProjectId, ProjectName, ProjectDescription ,ClientName ,Duration, "
+ " Manpower, ProjectStatus FROM TFS_mstrProject WHERE pStatus = 'Y'", con);
con.Open();
da.Fill(dtbl);
con.Close();
json = JsonConvert.SerializeObject(dtbl);
}
catch (Exception ex)
{
json = ex.Message.ToString();
}
return json;
}
and my Response is like
"[
{
\"ProjectId\":1.0,
\"ProjectName\":\"Prematix Messanger - Android\",
\"ProjectDescription\":\"Basically it will be using for the internal communication of the office. this application mainly involves message conversation and attaching doc for both sender and receiver.\",
\"ClientName\":\"Prematix\",
\"Duration\":15.0,
\"Manpower\":4.0,
\"ProjectStatus\":\"Locked\"
}
]"
I think this is not JSON format. How can I convert this into JSON?
I have a application that need to communicate with another application.
In the first application I mentioned it as:
public List<ContactsBO> getZingyContactsByCompanyId(int companyId) throws Exception {
String url="http://localhost:8080/ZingyApp/getContactsToBSAByAccountId";
URL object=new URL(url);
JSONObject account = new JSONObject();
String accountId = "58fd8c58abced355f69bf0bb";
account.put("accountId", accountId);
HttpURLConnection conn = (HttpURLConnection) object.openConnection();
conn.setConnectTimeout(50000);
conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setRequestMethod("POST");
OutputStream os = conn.getOutputStream();
OutputStreamWriter wr = new OutputStreamWriter(os);
wr.write(account.toString());
wr.flush();
os.close();
String json_response = "";
BufferedReader br = null;
if (conn.getResponseCode() == 200) {
br = new BufferedReader(new
InputStreamReader(conn.getInputStream()));
} else {
br = new BufferedReader(new
InputStreamReader(conn.getErrorStream()));
}
String text = "";
while ((text = br.readLine()) != null) {
json_response += text;
}
String contacts = json_response;
System.out.println("Contacts:"+contacts);
return null;
}
In second application I am trying to get the parameter accountId, which I set to a JSON object.
#RequestMapping(value="/getContactsToBSAByAccountId",method=RequestMethod.POST)
public #ResponseBody List<Contacts> getContactsByAccountId(#ModelAttribute("accountId") String accountId) {
System.out.println("Inside Account Details:"+accountId);
List<Contacts> contacts=salesContactService.getContactsByAccountId("58fd8c58abced355f69bf0bb");
return contacts;
}
Here accountId is null.
When I changed #RequestParams, the method itself is not getting called, and I got 400 error, when I change to #ModelAttribute only it gets called but values are not getting post.
Can someone give a suggestion on this one?
#RequestBody Map objectMap instead of ModelAttribute and get from map like String accountId = (String)objectMap.get("accountId")
This worked for me.
I am developing a search functionality in restful web service,from code i am passing searching string parameter to a method.i am getting the matched string response from database,Now how to validate whether input search string is exist or not from database.
public MemberEntity Search(string prefix)
{
try
{
MemberEntity ObjMember = new MemberEntity();
string sql = string.Format(#"select first_name, last_name from member_master where first_name like ('#prefix')");
using (MySqlConnection conn = new MySqlConnection(UtilityHelper.getConn()))
{
//using (MySqlCommand cmd = new MySqlCommand(string.Format("select first_name, last_name from member_master where first_name like ('#prefix%')"), conn))
using (MySqlCommand cmd = new MySqlCommand(sql.ToString(), conn))
{
conn.Open();
cmd.Parameters.AddWithValue("#prefix", prefix);
cmd.CommandType = CommandType.Text;
using (MySqlDataReader dr = cmd.ExecuteReader())
{
while (dr.Read())
{
ObjMember.Name = string.Format("{0} {1}", dr["first_name"].ToString(), dr["last_name"].ToString());
}
}
}
}
return ObjMember;
}
catch (Exception ex)
{
throw ex;
}
#endregion
}
Your sql should be like this.
string sql = string.Format(#"select first_name, last_name from member_master where first_name like '" + #prefix + "%'");
Currently, I am creating an application using ASP.NET MVC3 and MySQL and when I try to retrieve a user's first name from the databse I receive a System.FormatException: Input string was not in a correct format.
This is my code:
public string GetUserFirstName(UInt64 id)
{
DBConnections databaseCnnString = new DBConnections();
string connectionString = "server=123.123.com;user=me;database=db1;port=3306;password=abcdef";
MySqlConnection cnn = new MySqlConnection(connectionString);
try
{
cnn.Open();
string sp_GetFName = "SP_GET_FNAME";
MySqlCommand cmd = new MySqlCommand(sp_GetFName, cnn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("id", id);
cmd.Parameters["id"].Direction = ParameterDirection.Input;
cmd.Parameters.AddWithValue("first_name", MySqlDbType.VarChar);
cmd.Parameters["first_name"].Direction = ParameterDirection.Output;
object result = cmd.ExecuteScalar();
if (result != null)
{
string fname = Convert.ToString(result);
return fname;
}
else
{
string fname = "friend";
return fname;
}
}
catch (Exception ex)
{
throw (ex);
}
finally
{
cnn.Close();
cnn.Dispose();
}
}
This is MySQL Stored Procedure:
CREATE DEFINER=`0001`#`%` PROCEDURE `SP_GET_FNAME`(IN id BIGINT(20), OUT first_name VARCHAR(60))
BEGIN
DECLARE user_id BIGINT(20) DEFAULT id;
DECLARE output VARCHAR(60);
SELECT `FName` FROM `users` WHERE USERID=user_id INTO output;
SET first_name = output;
END
The problem seems to be when executing cmd.ExecuteScalar().
What is my problem here?
Thank you in advance!
Copy and paste error on my part. The correct code that works as expected is:
public string GetUserFirstName(UInt64 id)
{
DBConnections databaseCnnString = new DBConnections();
string connectionString = "server=123.123.com;user=me;database=db1;port=3306;password=abcdef";
MySqlConnection cnn = new MySqlConnection(connectionString);
try
{
cnn.Open();
string sp_GetFName = "SP_GET_FNAME";
MySqlCommand cmd = new MySqlCommand(sp_GetFName, cnn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("id", id);
cmd.Parameters["id"].Direction = ParameterDirection.Input;
cmd.Parameters.Add(new MySqlParameter("first_name", MySqlDbType.VarChar));
cmd.Parameters["first_name"].Direction = ParameterDirection.Output;
cmd.ExecuteScalar();
string fname = Convert.ToString((cmd.Parameters["first_name"].Value));
return fname;
}
catch (Exception ex)
{
throw (ex);
}
finally
{
cnn.Close();
cnn.Dispose();
}
}
CORRECTION: cmd.Parameters.Add(new MySqlParameter("first_name", MySqlDbType.VarChar));
NOT: cmd.Parameters.AddWithValue("first_name", MySqlDbType.VarChar);
In my case, the FNAME field in the user table cannot be NULL; therefore, checking for NULL values returned in the code is not necessary.
I would guess that the user is not found or the fname is null.
And I really hope you're not querying the database for each user column.
Good luck.
An additional comment.
When trying to return a string value the AddWithValue appears to be trying to convert the output from a string into a number. This results in the string format exception.