none
Newbie question about Parse JSon data RRS feed

  • Question

  • Hello:

    I can use HTTP request to post some json data to login a web portal, and the following is the response in XML format:

    <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
    <login-response>
    <session-token>12345_67890_xzys</session-token>
    <user-id>12345</user-id>
    <account>
    <address>
    <address-line-1>Main Street 123</address-line-1>
    <address-line-2>Toronto</address-line-2>
    <country>
    <country-id>001</country-id>
    <name>Canada</name>
    <country-code>CA</country-code>
    </country>
    <post-code>K1Z AB2</post-code>
    <region-name>Toronto</region-name>
    <address-id>500000</address-id>
    </address>
    </account>
    <last-login>2018-04-28T18:57:16Z</last-login>
    </login-response>

    I have to parse the <session-token> string, therefore, I do further data processing.

    However, I can't find any good way to parse such JSon data, if I want to create a file to include such XML format; but C# will NOT allow variable names with "-" inside.  If I want to parse such XML file, then what I can do?

    By the way, I found some new technology like ServiceStack can also do JSon parse, but I can't figure how to use any JsonSerializer and/or Deserializer can do the job.

    If you have any good idea, please share your code, esp., how to avoid using the illegal variable name.

    Thanks,

    Saturday, April 28, 2018 10:46 PM

Answers

  • Hi zydjohn,

    Thank you for posting here.

    For your question, you want to know how to parse the JSON data and get the properties in it, we can use JObject.Parse method to parse JSON string and get the information we want using the format: obj["session-token"], which is also applied for nested JSON. Below is the demo for your reference. 

    /*
    1. add reference Newtonsoft.Json
    2. import namespace Newtonsoft.Json.Linq;
    */
    //specify the path of the JSON data
    string path = "data.json";
        using (StreamReader sr = new StreamReader(path))
        {
    //get JSON string from file
            string data = sr.ReadToEnd();
    //parse the JSON string
            JObject obj = JObject.Parse(data);
    //get the property of session-token
            string session_token = obj["session-token"].ToString();
            string country_code = obj["account"]["address"]["country"]["country-code"].ToString();
            string address_id = obj["account"]["address"]["address-id"].ToString();
            Console.WriteLine("session-token:{0}, country-code:{1}, address-id:{2}", session_token, country_code, address_id);
            Console.ReadKey();
        }

    Please note that, you could create a json file directly from the your project. Right click the project> Add > New Item> JSON file. But you need to specify the path.

    Result of code.

    Best Regards,

    Wendy


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.


    Monday, April 30, 2018 7:35 AM
    Moderator

All replies

  • Since this is XML, then use an XML parser. For example:

    using System.Xml.Linq;

    using System.Xml.XPath;

    . . .

    string text = . . .

    XDocument d = XDocument.Parse( text );

    string session_token = d.XPathSelectElement( "login-response/session-token" ).Value;

     

    where text is a variable that contains the XML response.

    It is also possible to extract the values into an object (class), which requires more work based on XmlSerializer class.


    • Edited by Viorel_MVP Sunday, April 29, 2018 6:20 AM
    Sunday, April 29, 2018 6:17 AM
  • Hello:

    Thanks for your reply, I didn't realize that I uploaded the wrong format data, I can parse XML file.  For login to the web portal, the web server can reply with different format of data, one is XML, another is JSon.  But inside the web portal, if I want to do more data processing, then most of the data are in JSon format.

    The following is the JSon format data for the corresponding web portal login reply:

    {
    "session-token": "12345_67890_xzys",
    "user-id": 12345,
    "role": "USER",
    "account": {
    "address": {
    "country": {
    "country-id": 1,
    "name": "Canada",
    "country-code": "CA"
    },
    "address-id": 500000,
    "address-line-1": "Main Street 123",
    "address-line-2": "Toronto",
    "region-name": "Toronto",
    "post-code": "K1Z AB2"
    },
    "last-login": "2018-04-28T23:14:51.000Z"
    }

    For XML, it is rather easy, as we can use XPath, then no matter what is inside the XML file, we can parse the XML file and get the necessary information we want.  But for this kind of JSon data, if I want to get the "session-token", then what I should do?

    By the way, it is also interesting to know, how I can get the nested JSon data, like the "country-code" and "address-id"?

    By the way, for this login reply, I showed about only part of it, the original JSon data are rather lengthy, but have the same structure, to avoid complexity, only the important part of JSon data are shown, the other unnecessary parts are trimmed.

    Please advise how to parse the JSon data and get "session-token",  "country-code" and "address-id"?

    Thanks,

    Sunday, April 29, 2018 8:27 AM
  • Hi zydjohn,

    Thank you for posting here.

    For your question, you want to know how to parse the JSON data and get the properties in it, we can use JObject.Parse method to parse JSON string and get the information we want using the format: obj["session-token"], which is also applied for nested JSON. Below is the demo for your reference. 

    /*
    1. add reference Newtonsoft.Json
    2. import namespace Newtonsoft.Json.Linq;
    */
    //specify the path of the JSON data
    string path = "data.json";
        using (StreamReader sr = new StreamReader(path))
        {
    //get JSON string from file
            string data = sr.ReadToEnd();
    //parse the JSON string
            JObject obj = JObject.Parse(data);
    //get the property of session-token
            string session_token = obj["session-token"].ToString();
            string country_code = obj["account"]["address"]["country"]["country-code"].ToString();
            string address_id = obj["account"]["address"]["address-id"].ToString();
            Console.WriteLine("session-token:{0}, country-code:{1}, address-id:{2}", session_token, country_code, address_id);
            Console.ReadKey();
        }

    Please note that, you could create a json file directly from the your project. Right click the project> Add > New Item> JSON file. But you need to specify the path.

    Result of code.

    Best Regards,

    Wendy


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.


    Monday, April 30, 2018 7:35 AM
    Moderator
  • Hi, Wendy Zang:

    Thank you very much, your code works.

    However, now I have more complicated JSon files, I want to figure out how to parse them myself.  But I don't know which tools I can use, i.e: for XML file, I can find some online XPath tools to help me.  But for JSon data, is there any online tools like XPath which can help?

    Thanks,

    Monday, April 30, 2018 9:57 PM
  • Hi zydjohn,

    Thanks for your feedback.

    Try online tool JSONPath for JSON data.
    JSON Path tool link: http://jsonpath.com/

    Hope this help you.

    Best Regards,

    Wendy

    Note: This response contains a reference to a third-party World Wide Web site. Microsoft is providing this information as a convenience to you.
    Microsoft does not control these sites and has not tested any software or information found on these sites; Therefore, Microsoft cannot make any representations regarding the quality, safety, or suitability of any software or information found there.
    There are inherent dangers in the use of any software found on the Internet, and Microsoft cautions you to make sure that you completely understand the risk before retrieving any software from the Internet.


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.


    Monday, May 7, 2018 1:36 AM
    Moderator