如何将Json数组作为字段传递给WWWform

时间:2015-05-08 05:14:11

标签: arrays json unity3d

我想传递wwwform中的三个字段,其中包含两个单值和一个json数组。

这是我的Json:

{
     "Fname":"Abc",
     "Lname":"Xyz",
     "Marks": [{"MarksA":"23","MarksB":"65" },
     {"MarksA":"24","MarksB":"56" } ]
   }

我目前的代码是

 void Start()
    {
        WWWForm form = new WWWForm();
        form.AddField("Fname", "Abc");
        form.AddField("Lname", "Xyz");
        //passing the array as string
        string Mymarks = "[{\"MarksA\":\"23\",\"MarksB\":\"65\" },{\"MarksA\":\"24\",\"MarksB\":\"56\" } ]";
        form.AddField("Marks", Mymarks);
        WWW www = new WWW("Urltoservice", form);
        StartCoroutine("PostRequest", www);
    }
    IEnumerator PostRequest(WWW www)
    {
        yield return www;
        if (www.error == null)
        {
            Debug.Log("Session Saved");
        }
        else
        {
            Debug.Log("WWW Error: " + www.error);

        }
    }

但我得到了500 internal server Error。请帮我。

1 个答案:

答案 0 :(得分:0)

尝试使用WWW代替WWWForm

    using UnityEngine;

    using UnityEngine.UI;

    using System.Collections;

    using System.Collections.Generic;

    public class SendData : MonoBehaviour {

     void Start()
     {
         gameObject.GetComponent<Button>().onClick.AddListener(SendOnClick);
     }
     IEnumerator WaitForWWW(WWW www)
     {
         yield return www;


         string txt = "";
         if (string.IsNullOrEmpty(www.error))
             txt = www.text;  //text of success
         else
             txt = www.error;  //error
         GameObject.Find("TextDemo").GetComponent<Text>().text =  "--------\n\n" + txt;
     }
     void SendOnClick()
     {
         try
         {
             GameObject.Find("TextDemo").GetComponent<Text>().text = "Starting..";   
             string ourPostData = "{\"MarksA\":\"23\",\"MarksB\":\"65\" },{\"MarksA\":\"24\",\"MarksB\":\"56\" }";
             Dictionary<string,string> headers = new Dictionary<string, string>();
             headers.Add("Content-Type", "application/json");
             byte[] jData = System.Text.Encoding.ASCII.GetBytes(ourPostData.ToCharArray());
             WWW api = new WWW("YOUR URL", jData, headers);
             StartCoroutine(WaitForWWW(api));
         }
         catch (UnityException ex) { Debug.Log(ex.message); }
     }

    }