簡體   English   中英

簡單的JSON.NET序列化/反序列化示例

[英]Simple JSON.NET serialization/deserialization example

我一直在互聯網上搜索數小時,試圖用C#中的JSON調用找到一個非常簡單的序列化和反序列化示例。 在仔細瀏覽並拼接之后,我想在我的Web服務中調用JSON(POST和GET)功能(請參見下文)。

這就是我能夠拼湊的東西

這將是我的服務合同(IExecWebservice.svc)

using System.ServiceModel;
using System.ServiceModel.Web;

namespace _27963199
{
    [ServiceContract]
    public interface IExecFunction
    {
        [WebGet(UriTemplate = "/{function}/{args}")]
        double CalcThis(string function, string args);
    }
}

在我的主代碼中,我解析出用戶請求URI(IExecFunction.cs)

//user will send variables in REST URI http://myCalcServer/CalcThis/MethodA/10,20
using FunctionLibrary;
using System;
using System.Reflection;

namespace _27963199
{
    public class ExecFunctionService : IExecFunction
    {
        public double CalcThis(string function, string args)
        {
             Type t = typeof(Functions);
             MethodInfo[] libraryFunctions = t.GetMethods(BindingFlags.Static | BindingFlags.Public);
             string[] arguments = args.Split(',');

             //Missing piece of code where I split the URI for the JSON function that will POST the data object to be be calculated by the DROOLS/Rules Engine and the results passed back to the users web browser
...
         }
     }
}

現在,在單獨的函數類中,我將得到類似這樣的內容(Function.cs)

using System;
using newton.json;
using System.Net.Http;

namespace FunctionLibrary
{
    public static class Functions
    {
        public static double DoMathA(string url, string arg1, string arg2)
        {
            double d1;
            double d2;

            if (!double.TryParse(arg1, out d1) || !double.TryParse(arg2, out d2))
            {
                throw new ArgumentException("Arguments to function 'DoMathA' must be numeric.");
            }

            //Data Object Format "{'myData':{'Id':'5','var1':'10','var2':'90'}}"
            myCalcObject = "{'myData':{'Id':'5', & arg1 & :'10', & arg2 & :'90'}}"
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); 
            request.Method = "POST"; 
            request.ContentType = "application/json; charset=utf-8"; 
            DataContractJsonSerializer ser = new DataContractJsonSerializer(data.GetType()); 
            MemoryStream ms = new MemoryStream(); 
            ser.WriteObject (myCalcObject)
            String json = Encoding.UTF8.GetString(ms.ToArray()); 
            StreamWriter writer = new StreamWriter(request.GetRequestStream()); 
            writer.Write(json); 
            writer.Close();
       }
}
...

//Missing piece of code where I want to return the results of the JSON PUT and GET to the calling webservice
//JSON output string looks like this {"YourResults":{"condition":"YourHairIsOnFire","alertlevel":100,"id":0}}
//return or parse (json) to XLMS on the users browser

 }

我需要幫助來填補空白,以便正確解析請求URI以將其傳遞到JSON函數中,並將答復JSON字符串轉換為xlms在用戶瀏覽器上。 有什么想法嗎?

更新:我嘗試只讓JSON部分作為獨立的C#類工作,但是在編譯時出現“ Expected class ...”錯誤。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Net.Http;
using System.Net;
using Newtonsoft.Json;

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(http://172.16.20.26:8080/myDrools/result); 
request.Method = "POST"; 
request.ContentType = "application/json; charset=utf-8"; 
DataContractJsonSerializer ser = new DataContractJsonSerializer(data.GetType()); 
MemoryStream ms = new MemoryStream(); 
ser.WriteObject ("{'myData':{'Id':'5','var1':'4.5','var2':'8.7'}}")
String json = Encoding.UTF8.GetString(ms.ToArray()); 
StreamWriter writer = new StreamWriter(request.GetRequestStream()); 
writer.Write(json); 
writer.Close();

我在這里做錯了什么? 如何從中獲得XMLS輸出?

您有一些零碎的東西。 如果將它們粘合在一起,則可以正常工作。

服務介面

確保您的接口能夠返回包含您希望返回的數據的對象。 通過使字段可為空,您可以改變結果的外觀。

注意, ResponseFormat=WebMessageFormat.Json將json作為返回的內容類型。

[ServiceContract]
public interface IExecFunction
{
    [WebGet(UriTemplate = "/{function}/{args}", ResponseFormat=WebMessageFormat.Json)]
    [OperationContract]
    Result CalcThis(string function, string args);
}

// the result class that actsd as an container
public class Result
{
    public Double DoubleResult { get; set; }
    public Int32 IntResult { get; set; }
    public string Message { get; set; }
}

服務實施

服務實現涉及更多,因為它首先需要解析參數並將其轉換為適當的類型。 完成后,可以使用反射找到合適的方法來調用。 然后,將返回的類型轉換/投影到Result

public class ExecFunctionService : IExecFunction
{
    // this is a GET  /fubar/1,2,3,4
    public Result CalcThis(string function, string args)
    {
        // function=fubar
        // args = 1,2,3,4
        var allargs = args.Split(',');

        // store each argument with their type
        var typeList = new List<Tuple<Type, object>>();
        // parsr to gind the best match
        foreach(var arg in allargs)
        {
            // convert each argument string
            // to a type that is supported
            int i;
            if (Int32.TryParse(arg, out i))
            {
                typeList.Add(new Tuple<Type,object>(typeof(Int32), i));
                continue;
            }
            double d;
            if (Double.TryParse(arg, 
                   NumberStyles.AllowDecimalPoint,
                   new CultureInfo("en-us"), 
                   out d))
            {
                typeList.Add(new Tuple<Type,object>(typeof(Double), d));
                continue;
            }
            // if all fails assume string
            typeList.Add(new Tuple<Type,object>(typeof(string), arg));
        }

        // find and call the correct method
        // notice that parameters and their type do matter
        // overloads of the same methodname with 
        // different types is supported
        // Functions is the static type with methods to call
        var method = typeof(Functions).GetMethod(
            function,
            BindingFlags.Static| BindingFlags.Public |BindingFlags.InvokeMethod,
            null, 
            typeList.Select(ty => ty.Item1).ToArray(), //all types
            null);
        var callresult = method.Invoke(
            null, 
            typeList.Select(ty => ty.Item2).ToArray()); // all values

        // shape the output in the form you need
        var result = new Result();
        if(callresult is double)
        {
            result.DoubleResult = (double) callresult;
        }
        if (callresult is int)
        {
            result.IntResult = (int)callresult;
        }
        if (callresult is string)
        {
            result.Message = (string)callresult;
        }

        return result;
    }
}

您要調用的功能

此類包含可從服務調用的所有方法。

// your calc functions go here
public static class Functions
{
    public static double DoMathA(double arg1, double arg2)
    {
        return arg1 / arg2;
    }

    public static double DoMathB(int number, double factor)
    {
        return number * factor;
    }

    public static int DoMathC(string somestring)
    {
        return somestring.GetHashCode();
    }
}

它是什么樣子的?

調用http://localhost/service1.svc/DoMathC/fubar將返回:

{"DoubleResult":0,"IntResult":418978654,"Message":null}

http://localhost/service1.svc/DoMathA/2.5,3.4將返回:

{"DoubleResult":0.73529411764705888,"IntResult":0,"Message":null}

並且http://localhost/service1.svc/DoMathB/4,3.5將返回:

{"DoubleResult":14,"IntResult":0,"Message":null}

這樣考慮:返回一個對象而不是試圖將一個字符串粘在一起。 該服務將為您進行字符串化處理。 因此,創建一個具有與JSON對象匹配的屬性的類,然后將值設置為這些屬性,然后返回該對象。 完成。 不要想太多

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM