Json to String不起作用

时间:2017-01-02 17:42:06

标签: c# json

我的软件出现问题。它在标签中显示为json代码,但我使用Serialization将其转换为String,但它仍然以Json格式显示。此数据来自数据库。

using System;
using System.IO;
using System.Net;
using System.Windows;
using System.Web.Script.Serialization;




namespace MMPI2_Test
 {
   /// <summary>
/// Interaktionslogik für Patient.xaml
/// </summary>
public partial class Patient : Window
{
    public Patient()
    {
        InitializeComponent();
        Loaded += MyWindow_Loaded;
    }

    private void btyes_Click(object sender, RoutedEventArgs e)
    {

    }
    public String MyProperty { get; set; }

    public String Property { get; set; }
    private void MyWindow_Loaded(object sender, RoutedEventArgs e)
    {
        //dynamic convert = JsonConvert.DeserializeObject(MyProperty);

        string json = new JavaScriptSerializer().Serialize(MyProperty);
        lbuser.Content = json;


        string tan ="";
        MainWindow main = new MainWindow();
        main.alpha = tan;

        string html = string.Empty;
        string url = @"http://aa.workloud.at/?tag=question&token="+Property;

        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
        request.AutomaticDecompression = DecompressionMethods.GZip;

        using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
        using (Stream stream = response.GetResponseStream())
        using (StreamReader reader = new StreamReader(stream))
        {
            html = reader.ReadToEnd();
        }
        //dynamic magic = JsonConvert.DeserializeObject(html);
        string json2 = new JavaScriptSerializer().Serialize(html);
        lbquestion.Content = json2;

          }
         }
       }

编辑:

        <?php

   /**
   PHP API for MMPI2 Soul - lution
   **/

 header("Content-type: application/json");

 require_once("include/functions.php");
 require_once 'include/DB_Functions.php';

 $db = new DB_Functions();

 $tag = getParamValue("tag");
 $token = getParamValue("token");

 $response = array("data" => null, "tag" => $tag, "error" => null);

   if($token != null)
  {
  $checkToken = $db->validateToken($token);

  if($checkToken === true)
    {
    if($tag == "login")
        {
        global $currentTestName, $currentPatientTestId;
        $response["data"]["fname"] = $currentUser["firstname"];
        $response["data"]["lname"] = $currentUser["lastname"];
        $response["data"]["testname"] = $currentTestName;

        if ($db->startTest() !== true)
        {
            //$response["error"] = "Der Test hat schon eine StartTime";
        }

        }
    elseif($tag == "question")
    {
        // Request type is question
        // list questions
        $questions = $db->listQuestion();
        //echo var_dump($questions);
        if ($questions != false)
        {
            $response["data"] = $questions;
        }
        else
        {
            $response["error"] = "Fehler beim Laden der Fragen (keine Datensätze?)";
        }
    }
    elseif ($tag == 'answeredquestion')
    {
        // Request type is insert a answered question
       $qid = getParamValue('qid');
       $answer = getParamValue('answer');


        // store question
        $question = $db->storeQuestion($qid, $answer);

        if ($question != false)
        {
            // question stored successfully
        }
        else
        {
            // question failed to store
            $response["error"] = "JSON Error occured in saving new question.";
        }
    }
    elseif ($tag == "deletequestion")
    {   
        // delete question
        $question = $db->deleteQuestion();
        //echo var_dump($question);

        if ($question != false)
        {
            // delete question success
        }
        else
        {
            // delete question error
            $response["error"] = "Sie sind noch bei der ersten Frage.";
        }
    }
    elseif ($tag == "solution")
    {   
        // solution
        $solution = $db->setTestDone();
        //echo var_dump($solution);

        if ($solution != false)
        {
            // Evaluation success
            $response["data"] = $solution;
        }
        else
        {
            // Evaluation error
            $response["error"] = "Fehler beim Abschließen des Tests.";
        }
    }
    elseif ($tag == "addpatient" && $isAdmin)
    {
        // Request type is insert a patient
       $pid = getParamValue('pid');
       $svnr = getParamValue('svnr');
       $fname = getParamValue('fname');
       $lname = getParamValue('lname');
       $gender = getParamValue('gender');
       $age = getParamValue('age');
       $created_at = getParamValue('created_at');

        // Add patient
        $patient = $db->addPatient($pid, $svnr, $fname, $lname, $gender, $age, $created_at);

        if ($patient != false)
        {
            // patient stored successfully
        }
        else
        {
            // patient failed to store
            $response["error"] = "JSON Error occured in saving new patient.";
        }
    }
    elseif ($tag == "assigntest" && $isAdmin)
    {
        // Request type is assign test to a patient
       $pid = getParamValue('pid');
       $tid = getParamValue('tid');
       $sessiontoken = getParamValue('sessiontoken');

        // Assign test
        $patienttest = $db->assignTest($pid, $tid, $sessiontoken);

        if ($patienttest != false)
        {
            // patient stored successfully
        }
        else
        {
            // patient failed to store
            $response["error"] = "JSON Error occured in saving new patient.";
        }
    }
    elseif($tag == "getsolutions" && $isAdmin)
    {
        // Request type is getsolutions
        // list solutions
        $solutions = $db->listSolutions();
        //echo var_dump($solutions);
        if ($solutions != false)
        {
            $response["data"] = $solutions;
        }
        else
        {
            $response["error"] = "Fehler beim Laden der Ergebnisse (keine Datensätze?)";
        }
    }
    elseif($tag == "getsolutionscale" && $isAdmin)
    {
        // Request type is getsolutionscale
        $soid = getParamValue('soid');

        // list rawvalue of each scale from a Session
        $solutionscale = $db->listSolutionScale($soid);

        if ($solutionscale != false)
        {
            $response["data"] = $solutionscale;
        }
        else
        {
            $response["error"] = "Fehler beim Laden der Rohwerte (keine Datensätze?)";
        }
    }
    else
    {
        // Tag ist ungültig
        $response["error"] = "Tag nicht implementiert ($tag)!";
    }
}
else
{
    // Token nicht gültig!
    $response["error"] = $checkToken; 
 } 
echo json_encode($response);
 }
  else
  {
    echo "PHP API for MMPI 2 Soul - lution"; 
  }
 ?>

修改 标签显示在{\&#34;数据\&#34; {&#34; \&#34; fname \&#34;:\&#34; Hassan \&#34; .... 结果应该是哈桑。我怎么能这样做

编辑2

        public MainWindow()
    {
        InitializeComponent();
    }



    public String alpha { get; set; }

    private void button_Click(object sender, RoutedEventArgs e)
    {              
        String tan = tbtan.Text;
        string html = string.Empty;
        string url = @"http://stidl.workcloud.at/?tag=login&token=" + tan;

        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
        request.AutomaticDecompression = DecompressionMethods.GZip;

        using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
        using (Stream stream = response.GetResponseStream())
        using (StreamReader reader = new StreamReader(stream))
        {
            html = reader.ReadToEnd();
        }



        Patient pat = new Patient();
        pat.MyProperty = html;


        pat.Property = tbtan.Text;

        pat.Show();

  }
}

}

3 个答案:

答案 0 :(得分:0)

使用结构很适合json序列化。

public String MyProperty { get; set; }

public String Property { get; set; }
[Serializable]
public struct MyStuff
{
        public string MyProperty;

}

private void MyWindow_Loaded(object sender, RoutedEventArgs e)
{
    MyStuff stuff = new MyStuff();
    stuff.MyProperty = MyProperty;
    String json= JsonConvert.SerializeObject(stuff);

    lbuser.Content = json;

答案 1 :(得分:0)

您的代码正在按照您的要求行事;将字符串(而不是HTML)转换为JSON对象,然后将lbuser.Content设置为该JSON。

如果您尝试从JSON中提取元素,则需要执行相反的操作;从JSON中提取字符串。 JSON.NET可能是最简单的方法,但如果您必须使用System.Web.Script.Serialization,则可以执行此操作:

var j = new System.Web.Script.Serialization.JavaScriptSerializer().DeserializeObject(html) as Dictionary<string, object>;
var d = j["data"] as Dictionary<string, object>;
lbuser.Content = d["fname"].ToString();

请注意,您发布的JSON在语法上是不正确的,您甚至没有向我们展示内容,因此我完全猜测您的真实JSON中可用的键是什么。在调试器中检查其内容。

答案 2 :(得分:0)

你想要达到什么目标?

private void MyWindow_Loaded(object sender, RoutedEventArgs e)
{
    //dynamic convert = JsonConvert.DeserializeObject(MyProperty);

    string json = new JavaScriptSerializer().Serialize(MyProperty);
    lbuser.Content = json;
}

使用javascript序列化程序(即创建JSON)对属性进行SERIALIZING,然后将json指定给lbuser.Content。

如果数据来自JSON,那么通常你会将它DESERIALIZE成一个镜像JSON属性的类或一个字典。