2014-12-18 2 views
0

"reader.Read()"안에 json 문자열을 만들고 싶습니다. 어떻게 할 수 있습니까? 이것은 내가 그래서 당신은 예를 들어 페이지를 요청할 수 있습니다 생성 있어요 API입니다 api.ashx? TABLENAME = CURRENCYSYMBOL & ID 누군가가 도움을 줄 수 = 5 희망C#의 SQL 쿼리에서 Json 문자열 작성

나는 데이터베이스에서 열 값에서 JSON을 만들고 싶습니다

**이의 보안에 대해 걱정하자, 그냥 단지 내가 reader.Read() 방법에서 **

public void ProcessRequest (HttpContext context) 
    { 
     context.Response.Clear(); 

      string tablename = context.Request.QueryString["tablename"]; 
      int ID = Int32.Parse(context.Request.QueryString["ID"]); 
      context.Response.ContentType = "text/html"; 

      SqlConnection sqlConnection1 = new SqlConnection(ConfigurationManager.ConnectionStrings["WorldViewDatabase"].ConnectionString); 
      SqlCommand cmd = new SqlCommand(); 
      SqlDataReader reader; 

      cmd.CommandText = "SELECT * FROM " + tablename "WHERE ID = " + ID; 
      cmd.CommandType = CommandType.Text; 
      cmd.Connection = sqlConnection1; 

      sqlConnection1.Open(); 

      reader = cmd.ExecuteReader(); 
      // Data is accessible through the DataReader object here. 
      while (reader.Read()) 
      { 
       //context.Response.Write(reader); 
      } 
      sqlConnection1.Close(); 

      context.Response.Write(ID); 
      context.Response.Write(tablename); 
      return; 
    } 
+0

은 * 데이터베이스에 저장된 json *입니까? 또는 데이터베이스의 열 값에서 json을 만들려고합니까? (또한 : json을 반환하는 경우 "text/html"이라고 주장하는 것이 이상하게 보일 것입니다. 여기에 지시문이 아닌'using' 문이 있어야합니다.) –

+0

사이드 노트 : 매개 변수가있는 쿼리를 사용하여 'SQL'주입을 방지하십시오 – Sybren

+0

데이터베이스의 열 값에서 json을 생성하고 싶습니다. – JamesJGarner

답변

2

당신은 얻을 수 없다 JSON 결과를 사용하는 내부 응용 프로그램입니다. 그리고 그런 행동조차도 필요하지 않습니다.

랩하면 데이터베이스 행 구상 클래스에서 다음 그냥 문서의에서 JSON.NET 라이브러리를

http://james.newtonking.com/json

봐를 사용하여 JSON으로 개체를 직렬화 : http://james.newtonking.com/json/help/index.html

편집

public class T1 {} 
public class T2 {} 

public void ProcessRequest (HttpContext context) 
{ 
    object data = null; 

    string tablename = context.Request.QueryString["tablename"]; 
    if(tablename == "T1") 
    { 
     data = LoadTable1Data(); 
    } 
    else if(tablename == "T2") 
    { 
     data = LoadTable2Data(); 
    } 
    else 
    { 
     throw new Exception("Unknown tablename: " + tablename); 
    } 

    string jsonData = JsonConvert.SerializeObject(data); 
    context.Response.Write(jsonData); 
} 

public List<T1> LoadTable1Data() 
{ 
    List<T1> list = new List<T1>(); 

    ... 
    SqlDataReader reader = cmd.ExecuteReader(); 
    while(reader.Read()) 
    { 
     list.Add(new T1()); // fill T1 object with row data 
    } 

    return list; 
} 
+0

테이블 당 내 DB 열이 변경되는 경우 – JamesJGarner

+0

각 테이블에 대해 래퍼 클래스를 만들 수 있습니다. 그리고 복잡한 객체를 json 형식으로 반환하십시오. – opewix

+0

어떻게 데이터베이스 클래스를 구체적인 클래스로 래핑합니까? – JamesJGarner