2011-11-03 1 views
2

총 newby 질문은 여기 있습니다. 몇 시간 씩 애써 왔습니다.VB.NET ASP.NET 2.0에서 JSON 사용

저는 실제로 JSON 데이터를 사용하고 작성하는 방법을 이해하려고합니다. 나는 온종일 인터넷 검색을하고 있었고 여기에서 내가 뭘 좋아하는지 이해하려고 시도했다. http://james.newtonking.com/projects/json/help/은 Newtonsoft DLL을 다운로드했다. 나는 그것이 않는 확신 ...하지만 내가 그것을 어떻게 보나요

{ 
    "CPU": "Intel", 
    "PSU": "500W", 
    "Drives": [ 
    "DVD read/writer" 
    /*(broken)*/, 
    "500 gigabyte hard drive", 
    "200 gigabype hard drive"  ] 
} 

과 :

StringBuilder sb = new StringBuilder(); 
StringWriter sw = new StringWriter(sb); 

using (JsonWriter jsonWriter = new JsonTextWriter(sw)) 
{ 
jsonWriter.Formatting = Formatting.Indented; 

jsonWriter.WriteStartObject(); 
jsonWriter.WritePropertyName("CPU"); 
jsonWriter.WriteValue("Intel"); 
jsonWriter.WritePropertyName("PSU"); 
jsonWriter.WriteValue("500W"); 
jsonWriter.WritePropertyName("Drives"); 
jsonWriter.WriteStartArray(); 
jsonWriter.WriteValue("DVD read/writer"); 
jsonWriter.WriteComment("(broken)"); 
jsonWriter.WriteValue("500 gigabyte hard drive"); 
jsonWriter.WriteValue("200 gigabype hard drive"); 
jsonWriter.WriteEnd(); 
jsonWriter.WriteEndObject(); 
} 

처럼 보이는 무언가를 창조해야 하는가? 어떻게 그것을 브라우저가 출력 할 수있는 객체로 바꾸는가?

내가 해결해야 할 첫 번째 단계는 JSON 파일/문자열을 만드는 방법이며, 다음 단계는 실제로 어떻게 사용하는 것인가하는 것입니다. 도움이된다면, 처음에 목표로 삼고있는 것은 MySQL 데이터베이스에서 생성 된 검색 페이지에서 AJAX Autocomplete를 사용할 수있는 것입니다. 간단한 SQL 쿼리를 작성하여 비슷한 결과를 반환 할 수 있기를 바랍니다. 위의,하지만 난 분명히 그것에 대해 모든 잘못 가고있다!

BTW, 위의 예제는 C#으로, 내가 성공적으로 VB로 프로세스를 변환 했으므로 사용하고있는 것이지만 모든 응답은 VB 예제로 많이 평가 될 것입니다!

답변

1

게시 된 지 약 2 년이 지났지 만 동일한 질문을했는데 그 질문이 실제로 답변되지 않았 음을 알았습니다. OP의 질문에 대답하기 위해 JSON 문자열을 얻습니다.

sb.toString() 
0

결론은 브라우저에 JSON 문자열을 다시 가져와야한다는 것입니다. 당신은 자바 스크립트 변수에 넣을 수 있습니다 (라인 엔더와 작은 따옴표를 정리하면됩니다). 또는 ajax 쿼리의 결과로 다시 전달하십시오.

우리는 실제로 서버와 클라이언트 측 모두에서 지원되며 아주 사용하기 쉽기 때문에 내장 된 자바 스크립트 직렬기를 사용합니다. 기존 개체를 사용하면,이 코드는 서버 측에서 진행된다고 가정 : 클라이언트 측에

''' <summary> 
''' This method safely serializes an object for JSON by removing all of the special characters (i.e. CRLFs, quotes, etc) 
''' </summary> 
''' <param name="oObject"></param> 
''' <param name="fForScript">Set this to true when the JSON will be embedded directly in web page (as opposed to being passed through an ajax call)</param> 
''' <returns></returns> 
''' <remarks></remarks> 
Public Function SerializeObjectForJSON(ByVal oObject As Object, Optional ByVal fForScript As Boolean = False) As String 

If oObject IsNot Nothing Then 
    Dim sValue As String 

    sValue = (New System.Web.Script.Serialization.JavaScriptSerializer).Serialize(oObject) 

    If fForScript Then 
     ' If this serialized object is being placed directly on the page, then we need to ensure that its CRLFs are not interpreted literlally (i.e. as the actual JS values) 
     ' If we don't do this, the script will not deserialize correctly if there are any embedded crlfs. 
     sValue = sValue.Replace("\r\n", "\\r\\n") 

     ' Fix quote marks 
     Return CleanString(sValue) 
    Else 
     Return sValue 
    End If 
Else 
    Return String.Empty 
End If 
End Function 

, 직렬화는 간단하다 : 개체를 직렬화 복원하면

// The result should be a json-serialized record 
    oRecord = Sys.Serialization.JavaScriptSerializer.deserialize(result.value); 

, 당신은 사용할 수는 직접 자바 스크립트의 속성을 다음 JSON을 생성의 측면에서

alert('CPU = ' + oRecord.CPU); 
+0

감사합니다. @ competent_tech 유용한 정보. 그게 내가 실제로 처리하려고하는 과정을 정리하는 데 도움이되었고, 이제는 위 코드에서 JSON 출력을 얻을 수있었습니다. deserialization 비트는 작동하지 않지만 모든 종류의 오류가 발생하며 변경 한 사항은 해결되지 않습니다! 나는 .NET 2.0과 VB를 사용하고 있기 때문에 이것에 대해서 생각하고있다. 인터넷으로 C# 예제를 얻었고 .NET 2.0에서 내장 Serializer가 얼마나 잘 지원되는지 100 % 확신하지 못했다. –

0

시도

public class HardwareInfo 
    { 
     [JsonProperty(PropertyName = "CPU")] 
     public string Cpu { get; set; } 
     [JsonProperty(PropertyName = "PSU")] 
     public string Psu { get; set; } 
     [JsonProperty] 
     public ICollection<string> Drives { get; set; } 
    } 

    public string SerializeHardwareInfo() 
    { 
     var info = new HardwareInfo 
     { 
      Cpu = "Intel", 
      Psu = "500W", 
      Drives = new List<string> { "DVD read/writer", "500 gigabyte hard drive", "200 gigabype hard drive" } 
     }; 

     var json = JsonConvert.SerializeObject(info, Formatting.Indented); 
     // { 
     // "CPU": "Intel", 
     // "PSU": "500W", 
     // "Drives": [ 
     //  "DVD read/writer", 
     //  "500 gigabyte hard drive", 
     //  "200 gigabype hard drive" 
     // ] 
     // } 
     return json; 
    } 

서식 인수는 선택 사항입니다. 행운을 빌어 요.

+0

감사합니다. VB를 사용하고있는 것을 제외하고는 더 간단 해 보이지만, VB에서는 변경하기가 쉽습니다. 마침내 초기 예제를 통해 JSON을 생성 할 수 있었지만 이제는 그 일을하는 데 어려움을 겪고 있습니다.아래 Competent_tech의 게시물에 대한 내 댓글보기 –