简体   繁体   中英

How to print values from JSON Type Object to console in C#

I am trying to write a console application using c# 2.0 which will consume my webservice and return results from the webmethod.

In my C# code, I am able to get my values from the webmethod, please see below sample code:

 // print results
            try
            {

                Type objtype = Type.GetType(crisresult.ToString());
                object obj = Activator.CreateInstance(objtype);

                Object[] mArgs = new Object[methodArgs.Length + 1];
                methodArgs.CopyTo(mArgs, 0);
                mArgs.SetValue(obj, methodArgs.Length);
                methodArgs = mArgs;

                Object result = mi.Invoke(service, methodArgs);           
                Console.WriteLine(result);            

            }
            catch (Exception e)
            {
                Console.WriteLine("Error invoking method '" + methodName + "'");
                Console.WriteLine(e);
            }
            Console.WriteLine("Press enter to continue...");
            Console.ReadLine();

Now in above code my results from my webmethod is returned perfectly in JSON Type so my Object result have JSON type of values for example:

{"FullName":"Mr Mahesh Sharma","Miles":0,"TierStatus":"IO","TierMiles":0,"MilesExpiry":0,"ExpiryDate":"30/03/2012 00:00:00","AccessToken":"106C9FD143AFA6198A9EBDC8B9CC0FB2CE867356222D21D45B16BEEB9A7F390B5E226665851D6DB9","ActiveCardNo":"00300452124","PersonID":8654110}

Above result, I want to print in console with below format:

FullName: Mr Mahesh Sharma
Miles: 0
TierStatus: IO
TierMiles:0
MilesExpiry:0
ExpiryDate:31 March 2012
AccessToken: 106C9FD143AFA6198A9EBDC8B9CC0FB2CE867356222D21D45B16BEEB9A7F390B5E226665851D6DB9
ActiveCardNo: 00300452124
PersonID: 8654110

You can use the following:

return Newtonsoft.Json.JsonConvert.SerializeObject( obj, Formatting.Indented );

Simple and clean.

Personally I'd use JSON.NET . Sample code:

using System;
using Newtonsoft.Json.Linq;

class Test
{
    static void Main()
    {
        string json = "{\"FullName\":\"Mr Mahesh Sharma\",\"Miles\":0,\"TierStatus\":\"IO\"," +
            "\"TierMiles\":0,\"MilesExpiry\":0,\"ExpiryDate\":\"30/03/2012 00:00:00\"," + 
            "\"AccessToken\":\"106C9FD143AFA6198A9EBDC8B9CC0FB2CE867356222D21D45B16BEE" + 
            "B9A7F390B5E226665851D6DB9\",\"ActiveCardNo\":\"00300452124\",\"PersonID\":8654110}";

        JObject parsed = JObject.Parse(json);

        foreach (var pair in parsed)
        {
            Console.WriteLine("{0}: {1}", pair.Key, pair.Value);
        }
    }
}

Output:

FullName: "Mr Mahesh Sharma"
Miles: 0
TierStatus: "IO"
TierMiles: 0
MilesExpiry: 0
ExpiryDate: "30/03/2012 00:00:00"
AccessToken: "106C9FD143AFA6198A9EBDC8B9CC0FB2CE867356222D21D45B16BEEB9A7F390B5E226665851D6DB9"
ActiveCardNo: "00300452124"
PersonID: 8654110

Note that the value in each pair is a JToken , which you can cast to the relevant type.

If your returned json is always in that format then You can also try using JavaScriptSerializer

Try following code:

class Result
{   
    public string FullName{get; set;}
    public int Miles {get;set;}
    public string TimerStatus {get;set;}
    public int TimerMiles {get;set;}
    public int MilesExpiry {get;set;}
    public DateTime ExpiryDate{get;set;}
    public string AccessToken {get;set;}
    public string ActiveCardNo {get;set;}
    public long PersonID {get;set;}
}

Then deserialize your string to C# object.

JavaScriptSerializer jsr = new JavaScriptSerializer();
Result res = jsr.Deserialize<Result>(/*your json string*/);

Console.Writeline("FullName:{0}\n"+"
                "Miles{1}\n" +
                "TimerStatus:{2}\n"+
                "TimerMiles:{3}\n"+
                "MilesExpiry:{4}\n"+
                "ExpiryDate:{5}"+
                "AccessToken:{6}"+
                "ActiveCardNo:{7}"+
                "PersonID:{8}",
                res.FullName, res.Miles,res.TimerStatus,res.TimerMiles,res.MilesExpiry,res.Expirydate,res.AccessToken,res.ActivecardNo,res.PersonID
                )

Output as you wanted:

FullName: Mr Mahesh Sharma
Miles: 0
TierStatus: IO
TierMiles:0
MilesExpiry:0
ExpiryDate:31 March 2012
AccessToken: 106C9FD143AFA6198A9EBDC8B9CC0FB2CE867356222D21D45B16BEEB9A7F390B5E226665851D6DB9
ActiveCardNo: 00300452124
PersonID: 8654110

More Info on how to use JavaScriptSerializer

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM