1

以下是尝试返回 JSON 字符串的 asp Web 服务输出(不确定是否返回 JSON 字符串)。

在此处输入图像描述

在 android 应用程序使用此字符串后,字符串如下:

GetCustomerListResponse{GetCustomerListResult=[{"VehicleID":"KL-9876","VehicleType":"Nissan","VehicleOwner":"Sanjiva"}];}

[我很确定它不是 json 字符串]。

我想知道我应该进行哪些更改,以便 android 程序使用 json 字符串。

提前非常感谢,下面提供了我完整的 aspx 代码和 android 代码。

安卓代码:

    package com.example.objectpass;


        import android.app.Activity;
        import android.os.Bundle;
        import android.util.Log;
        import android.widget.ArrayAdapter;
        import android.widget.Spinner;
        import android.widget.TextView;

        import org.json.JSONArray;
        import org.json.JSONObject;
        import org.ksoap2.*;
        import org.ksoap2.serialization.SoapObject;
        import org.ksoap2.serialization.SoapPrimitive;
        import org.ksoap2.serialization.SoapSerializationEnvelope;
        import org.ksoap2.transport.*;

        public class MainActivity extends Activity {
            TextView resultA;
            Spinner spinnerC;

            @Override
            public void onCreate(Bundle savedInstanceState) {
                String[] toSpinnerSum;
                toSpinnerSum = new String[9];

                super.onCreate(savedInstanceState);
                setContentView(R.layout.activity_main);
                spinnerC = (Spinner) findViewById(R.id.spinner1);
                resultA = (TextView) findViewById(R.id.textView2);

                final String NAMESPACE = "http://tempuri.org/";
                final String METHOD_NAME = "GetCustomerList";
                final String SOAP_ACTION = "http://tempuri.org/GetCustomerList";
                final String URL = "http://192.168.1.100/WebService4/Service1.asmx";

                SoapObject Request = new SoapObject(NAMESPACE, METHOD_NAME);
                SoapSerializationEnvelope soapEnvelope = new SoapSerializationEnvelope(
                        SoapEnvelope.VER11);
                soapEnvelope.dotNet = true;
                soapEnvelope.setOutputSoapObject(Request);
                AndroidHttpTransport aht = new AndroidHttpTransport(URL);



                try {
                    aht.call(SOAP_ACTION, soapEnvelope);
                    SoapObject response = (SoapObject) soapEnvelope.bodyIn;

                    JSONArray jArray = new JSONArray();

                    resultA.setText(response.toString());

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }

ASP 网络服务代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Script.Services;
using Newtonsoft.Json;

namespace WebService4
{
    /// <summary>
    /// Summary description for Service1
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
    // [System.Web.Script.Services.ScriptService]
    public class Service1 : System.Web.Services.WebService
    {

        [WebMethod]
       [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
        public string GetCustomerList()
        {
            Vehicle vehi = simpleCase();
            List<Vehicle> newL = new List<Vehicle> { vehi };
            string output = JsonConvert.SerializeObject(newL);
           // return newL;
            return output;
        }




        [WebMethod]
        public Vehicle simpleCase()
        {
            Vehicle obj = new Vehicle();
            obj.VehicleID = "KL-9876";
            obj.VehicleType = "Nissan";
            obj.VehicleOwner = "Sanjiva";
            return obj;
        }
    }



    public class Vehicle
    {
        public string VehicleID { get; set; }
        public string VehicleType { get; set; }
        public string VehicleOwner { get; set; }
    }

}
4

2 回答 2

1

您的 WCF 服务是 XML 和 JSON 的混合体。您需要将其更改为返回纯 JSON 的服务。

http://localhost:49476/JsonService.svc/vehiclelist然后,您可以使用 URL和访问您的 JSON 方法http://localhost:49476/JsonService.svc/randomvehicle(端口号在您的情况下会有所不同)。只需在您的网络浏览器中尝试即可。

您可能还想看看这个答案。除了这个答案,它还展示了如何使用 POST 请求向服务发送大量数据。

请注意,我没有为 WCF 服务使用任何 JSON 类。相反,W

IJsonService.cs:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;

namespace SimpleJsonService
{
    [ServiceContract]
    public interface IJsonService
    {
        [OperationContract]
        [WebGet(ResponseFormat = WebMessageFormat.Json,
           BodyStyle = WebMessageBodyStyle.Bare,
           UriTemplate = "/vehiclelist")]
        List<Vehicle> GetCustomerList();

        [OperationContract]
        [WebGet(ResponseFormat = WebMessageFormat.Json,
           BodyStyle = WebMessageBodyStyle.Bare,
           UriTemplate = "/randomvehicle")]
        Vehicle RandomVehicle();
    }


    [DataContract]
    public class Vehicle
    {
        [DataMember]
        public string VehicleID { get; set; }
        [DataMember]
        public string VehicleType { get; set; }
        [DataMember]
        public string VehicleOwner { get; set; }
    }
}

JsonService.svc.cs:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;

namespace SimpleJsonService
{
    public class JsonService : IJsonService
    {
        public List<Vehicle> GetCustomerList()
        {
            Vehicle vehicle = RandomVehicle();
            List<Vehicle> vehicleList = new List<Vehicle> { vehicle };
            return vehicleList;
        }

        public Vehicle RandomVehicle()
        {
            Vehicle vehicle = new Vehicle();
            vehicle.VehicleID = "KL-9876";
            vehicle.VehicleType = "Nissan";
            vehicle.VehicleOwner = "Sanjiva";
            return vehicle;
        }
    }
}

JsonService.svc:

<%@ ServiceHost Language="C#" Debug="true" Service="SimpleJsonService.JsonService" CodeBehind="JsonService.svc.cs" Factory="System.ServiceModel.Activation.WebServiceHostFactory" %>

网络配置:

<?xml version="1.0"?>
<configuration>

  <appSettings>
    <add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" />
  </appSettings>
  <system.web>
    <compilation debug="true" targetFramework="4.5" />
    <httpRuntime targetFramework="4.5"/>
  </system.web>
  <system.serviceModel>
    <behaviors>
      <serviceBehaviors>
        <behavior>
          <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true"/>
          <serviceDebug includeExceptionDetailInFaults="false"/>
        </behavior>
      </serviceBehaviors>
    </behaviors>
    <protocolMapping>
        <add binding="basicHttpsBinding" scheme="https" />
    </protocolMapping>    
    <serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
  </system.serviceModel>
  <system.webServer>
    <modules runAllManagedModulesForAllRequests="true"/>
    <directoryBrowse enabled="true"/>
  </system.webServer>

</configuration>

在 Android 端,您需要使用 HTTPClient 和 JSONObject/JSONArray 来检索数据并对其进行解析。StackOverflow 上有很多例子展示了如何做到这一点。

于 2012-12-30T09:44:27.860 回答
1

嗨@Kasanova 将服务的响应格式设置为 json,如下所示:

 [OperationContract]
 [WebGet(UriTemplate = "data/id={value}", ResponseFormat = WebMessageFormat.Json)]
 string[] GetUser(string Id);
于 2012-12-31T08:52:26.640 回答