我如何消耗JSON字符串? [英] How do I consume a Json String?
问题描述
下面是ASP的 Web服务输出(不知道是否它返回一个JSON字符串)。
的Android应用程序消耗在此之后的字符串如下:
GetCustomerListResponse{GetCustomerListResult=[{\"VehicleID\":\"KL-9876\",\"VehicleType\":\"Nissan\",\"VehicleOwner\":\"Sanjiva\"}];}
[哪个IM pretty肯定,这是不是一个JSON字符串。
我想知道什么样的变化我应该做这样的Android程序会消耗一个JSON字符串。
下面提供了非常感谢提前和我的完整的aspx code和Android code。
ANDROID code:
包com.example.objectpass;
进口android.app.Activity;
进口android.os.Bundle;
进口android.util.Log;
进口android.widget.ArrayAdapter;
进口android.widget.Spinner;
进口android.widget.TextView; 进口org.json.JSONArray;
进口org.json.JSONObject;
导入org.ksoap2 *。
进口org.ksoap2.serialization.SoapObject;
进口org.ksoap2.serialization.SoapPrimitive;
进口org.ksoap2.serialization.SoapSerializationEnvelope;
导入org.ksoap2.transport *。 公共类MainActivity延伸活动{
TextView的resultA;
微调spinnerC; @覆盖
公共无效的onCreate(捆绑savedInstanceState){
的String [] toSpinnerSum;
toSpinnerSum =新的String [9]; super.onCreate(savedInstanceState);
的setContentView(R.layout.activity_main);
spinnerC =(微调)findViewById(R.id.spinner1);
resultA =(的TextView)findViewById(R.id.textView2); 最后弦乐NAMESPACE =http://tempuri.org/;
最后弦乐METHOD_NAME =GetCustomerList;
最后弦乐SOAP_ACTION =http://tempuri.org/GetCustomerList;
最终字符串URL =http://192.168.1.100/WebService4/Service1.asmx; SoapObject请求=新SoapObject空间(namespace,METHOD_NAME);
SoapSerializationEnvelope的SoapEnvelope =新SoapSerializationEnvelope(
SoapEnvelope.VER11);
soapEnvelope.dotNet = TRUE;
soapEnvelope.setOutputSoapObject(请求);
AndroidHttpTransport AHT =新AndroidHttpTransport(URL); 尝试{
aht.call(SOAP_ACTION,的SoapEnvelope);
SoapObject响应=(SoapObject)soapEnvelope.bodyIn; JSONArray jArray =新JSONArray(); resultA.setText(response.toString()); }赶上(例外五){
e.printStackTrace();
}
}
}
ASP WEB SERVICE code:
使用系统;
使用System.Collections.Generic;
使用System.Linq的;
使用的System.Web;
使用System.Web.Services;
使用System.Web.Script.Services;
使用Newtonsoft.Json;命名空间WebService4
{
///<总结>
///为服务1概要说明
///< /总结>
[WebService的空间(namespace =http://tempuri.org/)]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)
[System.ComponentModel.ToolboxItem(假)]
//要允许此Web服务从脚本调用,使用ASP.NET AJAX,取消注释以下行。
// [System.Web.Script.Services.ScriptService]
公共类服务1:System.Web.Services.WebService
{ [的WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)
公共字符串GetCustomerList()
{
车辆交通工具运动= simpleCase();
清单<汽车与GT; NEWL =新的List<汽车与GT; {}交通工具运动;
字符串输出= JsonConvert.SerializeObject(NEWL);
//返回NEWL;
返回输出;
}
[的WebMethod]
公车simpleCase()
{
车辆的obj =新车();
obj.VehicleID =KL-9876;
obj.VehicleType =日产;
obj.VehicleOwner =Sanjiva;
返回OBJ;
}
} 公共类车辆
{
公共字符串VehicleID {搞定;组; }
公共字符串VehicleType {搞定;组; }
公共字符串VehicleOwner {搞定;组; }
}}
您WCF服务是XML和JSON的混合物。你会希望把它变成一个返回纯JSON的服务。
您可以访问,然后使用您的URL JSON方法的http://本地主机:49476 / JsonService.svc / vehiclelist
和的http://本地主机:49476 / JsonService.svc / randomvehicle
(端口号会在你的情况有所不同)。只是尝试在Web浏览器。
您可能也想看看这个<一个href=\"http://stackoverflow.com/questions/835839/client-configuration-to-consume-wcf-json-web-service/4535043#4535043\">answer.除了这个答案,它展示了如何使用POST请求到大量的数据发送到服务。
请注意,我没有使用任何JSON类的WCF服务。相反,W
IJsonService.cs:
使用系统;
使用System.Collections.Generic;
使用System.Linq的;
使用System.Runtime.Serialization;
使用System.ServiceModel;
使用System.ServiceModel.Web;
使用System.Text;命名空间SimpleJsonService
{
[服务合同]
公共接口IJsonService
{
[OperationContract的]
[WebGet(ResponseFormat = WebMessageFormat.Json,
BodyStyle = WebMessageBodyStyle.Bare,
UriTemplate =/ vehiclelist)]
清单&LT;汽车与GT; GetCustomerList(); [OperationContract的]
[WebGet(ResponseFormat = WebMessageFormat.Json,
BodyStyle = WebMessageBodyStyle.Bare,
UriTemplate =/ randomvehicle)]
车辆RandomVehicle();
}
[DataContract]
公共类车辆
{
[数据成员]
公共字符串VehicleID {搞定;组; }
[数据成员]
公共字符串VehicleType {搞定;组; }
[数据成员]
公共字符串VehicleOwner {搞定;组; }
}
}
JsonService.svc.cs:
使用系统;
使用System.Collections.Generic;
使用System.Linq的;
使用System.Runtime.Serialization;
使用System.ServiceModel;
使用System.ServiceModel.Web;
使用System.Text;命名空间SimpleJsonService
{
公共类JsonService:IJsonService
{
公开名单&LT;汽车与GT; GetCustomerList()
{
车辆车辆= RandomVehicle();
清单&LT;汽车与GT; vehicleList =新的List&LT;汽车与GT; {}车辆;
返回vehicleList;
} 公车RandomVehicle()
{
车辆车辆=新车();
vehicle.VehicleID =KL-9876;
vehicle.VehicleType =日产;
vehicle.VehicleOwner =Sanjiva;
返回车辆;
}
}
}
JsonService.svc:
&LT;%@ ServiceHost的语言=C#调试=真正的服务=SimpleJsonService.JsonServicecodeBehind =JsonService.svc.cs厂=系统.ServiceModel.Activation.WebServiceHostFactory%GT;
的Web.config:
&LT;?XML版本=1.0&GT?;
&LT;结构&gt; &LT;&的appSettings GT;
&LT;添加键=ASPNET:UseTaskFriendlySynchronizationContextVALUE =真/&GT;
&LT; /的appSettings&GT;
&LT;&的System.Web GT;
&LT;编译调试=真targetFramework =4.5/&GT;
&LT;的httpRuntime targetFramework =4.5/&GT;
&LT; /system.web>
&LT; system.serviceModel&GT;
&LT;&行为GT;
&LT; serviceBehaviors&GT;
&LT;&行为GT;
&LT; serviceMetadata httpGetEnabled =真httpsGetEnabled =真/&GT;
&LT; serviceDebug includeExceptionDetailInFaults =FALSE/&GT;
&LT; /行为&GT;
&LT; / serviceBehaviors&GT;
&LT; /行为&GT;
&LT; protocolMapping&GT;
&LT;添加绑定=basicHttpsBinding计划=HTTPS/&GT;
&LT; / protocolMapping&GT;
&LT; serviceHostingEnvironment aspNetCompatibilityEnabled =真multipleSiteBindingsEnabled =真/&GT;
&LT; /system.serviceModel>
&LT; system.webServer&GT;
&LT;模块runAllManagedModulesForAllRequests =真/&GT;
&LT; directoryBrowse启用=真/&GT;
&LT; /system.webServer>&LT; /结构&gt;
在Android端,您需要使用和的HTTPClient的JSONObject / JSONArray检索数据并解析它。有迹象表明,展示如何做到这一点的计算器例子很多。
The following is a asp web service output that tries to return a JSON String (Not sure if it is returning a JSON string).
After the android application consumes this the string is as follows:
GetCustomerListResponse{GetCustomerListResult=[{"VehicleID":"KL-9876","VehicleType":"Nissan","VehicleOwner":"Sanjiva"}];}
[Which im pretty sure that it is not a json string].
I would like to know what changes I should be making so that the android program is consuming a json string.
Thanks a lot in advance, and my complete aspx code and android code are provided below.
ANDROID CODE:
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 WEB SERVICE CODE:
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; }
}
}
Your WCF service is a mixture of XML and JSON. You'll want to change it into a service that returns pure JSON.
You can then access your JSON methods using the URLs http://localhost:49476/JsonService.svc/vehiclelist
and http://localhost:49476/JsonService.svc/randomvehicle
(the port number will be different in your case). Just try it in your web browser.
You might also want to have a look at this answer. In addition to this answer, it shows how to use a POST request to send a lot of data to the service.
Note that I don't use any JSON classes for the WCF service. Instead, 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" %>
Web.config:
<?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>
On the Android side, you'll want to use HTTPClient and JSONObject/JSONArray to retrieve the data and parse it. There are many examples on StackOverflow that show how to do it.
这篇关于我如何消耗JSON字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!