2

what is the best way to write json object in c#? I have a piece of code which is supposed to get data from DB and write json object but I haven't had my mind clear about this

[WebMethod]
public static string get_specialities(string ProfessionalID)
{
    Database db = DatabaseFactory.CreateDatabase("Connection String2");
    DbCommand dbCommand;
    dbCommand = db.GetStoredProcCommand("select_Professionals_Speciality");
    db.AddInParameter(dbCommand, "prof_id", DbType.Int16, Convert.ToInt16(ProfessionalID));
    IDataReader dr = db.ExecuteReader(dbCommand);
    //[{ id: 3, name: "test3" }]
    string return_str="[";
    int i = 0;
    while (dr.Read()) {
        if (i > 0)
            return_str += ",";
        return_str += "{id:" + dr["SpecialtyID"].ToString().Trim() + ",name:" + dr["SpecialtyName"].ToString().Trim() + "}";
        i++;
    }
    return_str += "]";
    return return_str;
}

this returns the object below, which is in wrong format

{"d":"[{id:67,name:Kardiyoloji}]"}

what am I doing wrong?

1
  • NewtonSoft.JSON is what you looking for. And little sugestion use StringBuilder when you creating string it's make a different in performance Commented Apr 4, 2013 at 12:56

5 Answers 5

2

Try this using JavaScriptSerializer class:

List<Person> people = new List<Person>();
Person p = new Person();

while (dr.Read()) {
    p = new Person();
    p.id = dr["SpecialtyID"].ToString().Trim();
    p.name = dr["SpecialtyName"].ToString().Trim();
    people.Add(p);
}

JavaScriptSerializer serializer = new JavaScriptSerializer();
string return_str = serializer.Serialize(people);
Sign up to request clarification or add additional context in comments.

Comments

0

About the code you provided, the right json should be:

{"d":[{"id":67,"name":"Kardiyoloji"}]}

You can check with jsonlint: http://jsonlint.com/

Use a serializer. I suggest NewtonSoft. You can find a lot of samples around, otherwise ask for a snippet of code here

Comments

0

directly converting to string is not a good idea generally... you should use serialize such as jobs... but you can try like this

{"d":'[{"id":67,"name":"Kardiyoloji"}]'}

are you gonna deserialize value of d again ?

1 Comment

how can I return it as json object rather than string
0

I assumed that you don't know how to write special char in your string which is " double quota in your case?

replace: "{id:" + dr["SpecialtyID"].ToString().Trim() + ",name:" + dr["SpecialtyName"].ToString().Trim() + "}";

for

"{\"id\":" + dr["SpecialtyID"].ToString().Trim() + "\",\"name\":\"" + dr["SpecialtyName"].ToString().Trim() + "\"}";

will do what you need. But better way is using a NewtonSoft serializer for JSON handling.

Hope it help.

Comments

0

I suggest you to avoid manually building the JSON string.

Rather, map the db data into the corresponding object (entity?), and then serialize it into JSON.

You can use the Javascript Serializer. I also use the JayRock library.

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.