Click here to Skip to main content
15,891,903 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi,


I am trying to fetch the value from json into array but somewhere i am going wrong. It is working but not fully.

My JSON String is : {{"WorkingDays":"Monday, Tuesday, Wednesday"},{"WorkingTime":"10 AM : 7 PM, 11 AM : 2 PM, 4 PM : 4 AM"}}

The code in my business logic is as follows :
C#
public string wsOutletRegistration(string str)
{

  string[] O_WorkingDays = null;
  string[] O_WorkingTime = null;
  string WorkingTime = string.Empty;

  String[] para = str.Split('{', '}', '[', ']', ':', '"');

  for (int i = 0; i < para.Length; i++)
  {
    if (para[i].Equals("WorkingDays"))
                    WorkingDays = para[i + 3];
                else if (para[i].Equals("WorkingTimeFrom"))
                //WorkingTime = para[i + 3];
                {
                    string[] from = {"", "", "", ""," ", ""};
                    string[] to = { "", "", "", "", "", "" };
                    int k = 0;
                    int h = 0;
                    WorkingTime = para[i + 1];
                    for (int j = (i + 3); j < para.Length - 1; j++)
                        WorkingTime = WorkingTime + para[j];
                    O_WorkingTime = WorkingTime.Split(' ', ',');
                    for (int j = 0; j < O_WorkingTime.Length; j++)
                    {
                        from[k] = O_WorkingTime[j] + O_WorkingTime[j + 1];
                        to[k] = O_WorkingTime[j + 3] + O_WorkingTime[j + 4];
                        j = j + 2;
                        k++;
                    }
                }
  }


What i want to get is from[k] should contain the values like 10AM, 11AM, 4PM and to[k] should contain 7PM , 2PM and 4AM.

But i am getting the result as from[k] = 10AM, 7PM, 11AM, 2PM, 4PM, 4AM
and to[k] = 7PM, 11AM, 2PM, 4PM, 4AM.

So what i am needed to change in my code so that i can get the values i am expecting. Please help me out.

Thanks in advance.....
Posted
v2
Comments
WoodenLegNamedSmith 31-Jul-12 16:05pm    
You could set up a DataContract and use System.Runtime.Serialization.Json;
Would be way more efficient than trying to write your own parser.

1 solution

This is horrible code. Like someone else said, you should use a library that parses JSON properly, but, don't create an empty array and ASSUME the array coming in is the same size. Use the List class, and call ToArray at the end if you need to.

If I had to parse this, I'd split on the , the read each string, split on the : and put those two values in to the two lists. Your code is so convoluted right now, I'm not sure why it's going wrong, or how it's running.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900