0
   public Users GetUserById(string _id)
   {
        MySqlConnection conn = new MySqlConnection(connstr);
        conn.Open();
        string sql = ("select * from Books where id = " + _id);

        MySqlCommand cmd = new MySqlCommand(sql, conn);
        MySqlDataReader reader = cmd.ExecuteReader();
        Users obj = new Users();
        if (reader.Read())
        {
            obj.id = Convert.ToInt32(reader[0]);
            obj.UserName = reader[1].ToString();

        }
        reader.Close();
        conn.Close();
        return obj;
    }

I am puuling the info in Json Format but

Out Put for this is: {"UserName":"John","id":1}

Expected Out put is: [{"UserName":"John","id":1}]

I am missing the Square braces for the record Whats the problem with my code?

1
  • the operation contract for above code is[OperationContract] [WebGet(UriTemplate="User/{id}",ResponseFormat=WebMessageFormat.Json)] Users GetUserById(string id); Commented Jun 7, 2013 at 7:35

1 Answer 1

3

Your expected output i.e. [{"UserName":"John","id":1}] represents the List of Users object.

So if you want such output should return from your function then you just need to return a List of user from your function.

But as your function name GetUserById, I think it should return single user( So I don't know why are trying to return an array of users from this)

But anyway you can get the expected output in this way

public List<Users> GetUserById(string _id)
{
   MySqlConnection conn = new MySqlConnection(connstr);
   conn.Open();
   string sql = ("select * from Books where id = " + _id);

   MySqlCommand cmd = new MySqlCommand(sql, conn);
   MySqlDataReader reader = cmd.ExecuteReader();

   List<Users> users=new List<Users>();
   Users obj = new Users();
   if (reader.Read())
   {
     obj.id = Convert.ToInt32(reader[0]);
     obj.UserName = reader[1].ToString();
     users.Add(obj);
   }
   reader.Close();
   conn.Close();
   return users;
}

Now whenever this users convert into json format, it will return the expected output.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.