locked
Returning JSON Array RRS feed

  • Question

  • Good morning.

    I have a service that looks like the following:

    Interface

    <ServiceContract()> _
    Public Interface IUmbrellaMobileService
    
    
        <OperationContract()> _
           <WebInvoke(Method:="GET", BodyStyle:=WebMessageBodyStyle.Bare, ResponseFormat:=WebMessageFormat.Json)> _
        Function GetCustomers() As String
    End Interface

    The service.vb file looks like this ( I have shortened it ) :

    <AspNetCompatibilityRequirements(Requirementsmode:=AspNetCompatibilityRequirementsMode.Allowed)> _
    Public Class UmbrellaService
        Inherits System.Web.Services.WebService
        Implements IUmbrellaMobileService
    
        Function GetCustomers() As String Implements IUmbrellaMobileService.GetCustomers
    
            Try
                Dim Cust As List(Of Customers) = New List(Of Customers)
    
                Dim SQLSTR As String = ""
                SQLSTR = "Select Companies.Code, Companies.Name FROM Companies WHERE ISCustomer = '1'"
    
                Dim ErrorMessage As String = ""
                ErrorMessage = UmbrellaDataManagementObj.OpenConnection(SQLServer, UmbrellaDatabase, UserCode, UserPassword)
                If ErrorMessage <> "" Then
                    System.Diagnostics.EventLog.WriteEntry("Umbrella Mobile Service", ErrorMessage & vbNewLine & UmbrellaDataManagementObj.ConnectionString, EventLogEntryType.Error)
                    WebOperationContext.Current.OutgoingResponse.StatusCode = 501
                    WebOperationContext.Current.OutgoingResponse.StatusDescription = ErrorMessage
    
    
                    Return Nothing
                Else
                    Dim CustomerDetails As DataSet
                    CustomerDetails = UmbrellaDataManagementObj.GetDataSQL(SQLSTR)
                    If Not CustomerDetails Is Nothing Then
                        CustomerDetails.DataSetName = "Companies"
                        CustomerDetails.Tables(0).TableName = "Companies"
                        Dim CustomerTable As DataTable
                        Dim CustomerRow As DataRow
    
                        If CustomerDetails.Tables.Count > 0 Then
                            CustomerTable = CustomerDetails.Tables(0)
                            If CustomerTable.Rows.Count > 0 Then
    
                                Dim i As Integer
    
                                For i = 0 To CustomerTable.Rows.Count - 1
                                    CustomerRow = CustomerTable.Rows(0)
                                    Dim CC As New Customers
                                    CC.Code = CustomerRow.Item("Code")
                                    CC.Name = CustomerRow.Item("Name")
    
                                    Cust.Add(CC)
    
                                 
                                Next i
                                ' Serialize the results as JSON
                                Dim serializer As DataContractSerializer = New DataContractSerializer(Cust.GetType())
                                Dim Stream As MemoryStream = New MemoryStream
    
                                serializer.WriteObject(Stream, Cust)
    
                                ' Return the results serialized as JSON
                                Dim json As String = Encoding.Default.GetString(Stream.ToArray())
                                Return json
    
                                UmbrellaDataManagementObj.CloseConnection()
                                WebOperationContext.Current.OutgoingResponse.StatusCode = 200
                                WebOperationContext.Current.OutgoingResponse.StatusDescription = "OK"
                            End If
                        End If
    
    
    
                        'Return Cust
                    Else
                        System.Diagnostics.EventLog.WriteEntry("Umbrella Mobile Service", UmbrellaDataManagementObj.ErrorMessage, EventLogEntryType.Error)
    
                        WebOperationContext.Current.OutgoingResponse.StatusCode = 501
                        WebOperationContext.Current.OutgoingResponse.StatusDescription = UmbrellaDataManagementObj.ErrorMessage
    
                        Cust = Nothing
                        Return Nothing
                    End If
                End If
    
    
    
            Catch ex As Exception
                System.Diagnostics.EventLog.WriteEntry("Umbrella Mobile Service", ex.Message, EventLogEntryType.Error)
    
                WebOperationContext.Current.OutgoingResponse.StatusCode = 501
                WebOperationContext.Current.OutgoingResponse.StatusDescription = ex.Message
    
    
                Return Nothing
            End Try
            Dispose()
        End Function
    

    It works, but it returns XML instead of JSON, whic I find odd as I have used all JSON related stuff. The outout is :

    "<ArrayOfCustomers xmlns=\"http:\/\/schemas.datacontract.org\/2004\/07\/UmbrellaMobileService\" xmlns:i=\"http:\/\/www.w3.org\/2001\/XMLSchema-instance\"><Customers><Code>001<\/Code><Name>rainbow<\/Name><\/Customers><Customers><Code>001<\/Code><Name>rainbow<\/Name><\/Customers><Customers><Code>001<\/Code><Name>rainbow<\/Name><\/Customers><Customers><Code>001<\/Code><Name>rainbow<\/Name><\/Customers><Customers><Code>001<\/Code><Name>rainbow<\/Name><\/Customers><Customers><Code>001<\/Code><Name>rainbow<\/Name><\/Customers><Customers><Code>001<\/Code><Name>rainbow<\/Name><\/Customers><Customers><Code>001<\/Code><Name>rainbow<\/Name><\/Customers><Customers><Code>001<\/Code><Name>rainbow<\/Name><\/Customers><Customers><Code>001<\/Code><Name>rainbow<\/Name><\/Customers><Customers><Code>001<\/Code><Name>rainbow<\/Name><\/Customers><Customers><Code>001<\/Code><Name>rainbow<\/Name><\/Customers><Customers><Code>001<\/Code><Name>rainbow<\/Name><\/Customers><Customers><Code>001<\/Code><Name>rainbow<\/Name><\/Customers><Customers><Code>001<\/Code><Name>rainbow<\/Name><\/Customers><Customers><Code>001<\/Code><Name>rainbow<\/Name><\/Customers><Customers><Code>001<\/Code><Name>rainbow<\/Name><\/Customers><Customers><Code>001<\/Code><Name>rainbow<\/Name><\/Customers><Customers><Code>001<\/Code><Name>rainbow<\/Name><\/Customers><Customers><Code>001<\/Code><Name>rainbow<\/Name><\/Customers><Customers><Code>001<\/Code><Name>rainbow<\/Name><\/Customers><Customers><Code>001<\/Code><Name>rainbow<\/Name><\/Customers><Customers><Code>001<\/Code><Name>rainbow<\/Name><\/Customers><Customers><Code>001<\/Code><Name>rainbow<\/Name><\/Customers><Customers><Code>001<\/Code><Name>rainbow<\/Name><\/Customers><Customers><Code>001<\/Code><Name>rainbow<\/Name><\/Customers><Customers><Code>001<\/Code><Name>rainbow<\/Name><\/Customers><Customers><Code>001<\/Code><Name>rainbow<\/Name><\/Customers><Customers><Code>001<\/Code><Name>rainbow<\/Name><\/Customers><Customers><Code>001<\/Code><Name>rainbow<\/Name><\/Customers><Customers><Code>001<\/Code><Name>rainbow<\/Name><\/Customers><Customers><Code>001<\/Code><Name>rainbow<\/Name><\/Customers><Customers><Code>001<\/Code><Name>rainbow<\/Name><\/Customers><Customers><Code>001<\/Code><Name>rainbow<\/Name><\/Customers><Customers><Code>001<\/Code><Name>rainbow<\/Name><\/Customers><Customers><Code>001<\/Code><Name>rainbow<\/Name><\/Customers><Customers><Code>001<\/Code><Name>rainbow<\/Name><\/Customers><Customers><Code>001<\/Code><Name>rainbow<\/Name><\/Customers><Customers><Code>001<\/Code><Name>rainbow<\/Name><\/Customers><Customers><Code>001<\/Code><Name>rainbow<\/Name><\/Customers><Customers><Code>001<\/Code><Name>rainbow<\/Name><\/Customers><Customers><Code>001<\/Code><Name>rainbow<\/Name><\/Customers><Customers><Code>001<\/Code><Name>rainbow<\/Name><\/Customers><Customers><Code>001<\/Code><Name>rainbow<\/Name><\/Customers><Customers><Code>001<\/Code><Name>rainbow<\/Name><\/Customers><Customers><Code>001<\/Code><Name>rainbow<\/Name><\/Customers><\/ArrayOfCustomers>"

    I know it must just be some little setting to convert this output to JSON, but other than that, I do not know.

    Can anyone please help me to output JSON

    Thursday, September 10, 2015 6:36 AM

Answers

  • Hi HanneSThEGreaT,

    If you set ResponseFormat:=WebMessageFormat.Json  then you will get output as a json array.

    Why you need to use DataContractJsonSerializer to serialize it ?

    And I saw your result, I guess that is the array. And you want to remove "\".

    in my opinion is that you can convert the result as string.

    follow this:

    static void Main(string[] args)
        {
            DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(Person));
           
            string str = "{\"Id\":1,\"Name\":\"Tom\",\"Age\":\"23\"}";
            Person p;
            using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(str)))    
            {
                p = serializer.ReadObject(ms) as Person;
            }
            Console.WriteLine(p.Name);      
    
            Person p2 = new Person(2, "Vincen", 23);
            byte[] result;
            using (MemoryStream ms = new MemoryStream())
            {
                serializer.WriteObject(ms, p2);
    
                result = ms.ToArray();
            }
            Console.WriteLine(Encoding.UTF8.GetString(result));    
    }

    Then the output looks like this

    //output {"Age":23,"Id":2,"Name":"Vincen"}

    Best Regards,

    Vince Li

    • Proposed as answer by Grady_Dong Monday, September 21, 2015 6:41 AM
    • Marked as answer by Grady_Dong Thursday, September 24, 2015 12:36 AM
    Wednesday, September 16, 2015 8:54 AM

All replies

  • OK, I am an idiot.... I had to use DataContractJsonSerializer. Right, that works fine; but, I would like to take away the unnecessary "\". My output looks like :

    "[{\"Code\":\"001\",\"Name\":\"rainbow\"},{\"Code\":\"001\",\"Name\":\"rainbow\"},{\"Code\":\"001\",\"Name\":\"rainbow\"},{\"Code\":\"001\",\"Name\":\"rainbow\"}]"

    I need to take away the escape characters, please


    Thursday, September 10, 2015 6:56 AM
  • Hi HanneSThEGreaT,

    If you set ResponseFormat:=WebMessageFormat.Json  then you will get output as a json array.

    Why you need to use DataContractJsonSerializer to serialize it ?

    And I saw your result, I guess that is the array. And you want to remove "\".

    in my opinion is that you can convert the result as string.

    follow this:

    static void Main(string[] args)
        {
            DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(Person));
           
            string str = "{\"Id\":1,\"Name\":\"Tom\",\"Age\":\"23\"}";
            Person p;
            using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(str)))    
            {
                p = serializer.ReadObject(ms) as Person;
            }
            Console.WriteLine(p.Name);      
    
            Person p2 = new Person(2, "Vincen", 23);
            byte[] result;
            using (MemoryStream ms = new MemoryStream())
            {
                serializer.WriteObject(ms, p2);
    
                result = ms.ToArray();
            }
            Console.WriteLine(Encoding.UTF8.GetString(result));    
    }

    Then the output looks like this

    //output {"Age":23,"Id":2,"Name":"Vincen"}

    Best Regards,

    Vince Li

    • Proposed as answer by Grady_Dong Monday, September 21, 2015 6:41 AM
    • Marked as answer by Grady_Dong Thursday, September 24, 2015 12:36 AM
    Wednesday, September 16, 2015 8:54 AM