0

I have this json string:

[ 
   {f_id:100,r_id:200,count:2,c_id=111},
   {f_id:120,r_id:200,count:1,c_id=111 }
]


i want to parse up json string with newtonsoft.json.
how can i do this?

I write this code:

private void button1_Click(object sender, EventArgs e)
    {
        string json = @"[ 
{f_id:100,r_id:200,count:2,c_id=111},
{f_id:120,r_id:200,count:1,c_id=111 }
]";
        List<myClass> tmp = JsonConvert.DeserializeObject<List<myClass>>(json);
        int firstFId = tmp[0].f_id;
        label1.Text = firstFId.ToString();
        label2.Text = tmp[1].f_id.ToString();



    }

    public class myClass
    {
        public int f_id { get; set; }
        public int r_id { get; set; }
        public int count { get; set; }
        public int c_id { get; set; }


    }


but have this error:

An unhandled exception of type 'Newtonsoft.Json.JsonReaderException' occurred in    Newtonsoft.Json.dll

Additional information: Invalid JavaScript property identifier character: =. Path '[0].count', line 2, position 32.
  • Do you want to parse it into a class, or simply an intermediate object? – Yuval Itzchakov Aug 08 '14 at 05:42
  • There are plenty of examples and answered questions available. Are they not helping you to solve your problem? For example, http://stackoverflow.com/questions/18242429/how-to-deserialize-json-data. If not, then be more specific with exact problem you are facing. – SBirthare Aug 08 '14 at 05:44

1 Answers1

0

Create a class that represents the data.

public class MyClass {
   public int f_id { get; set; }
   public int r_id { get; set; }
   public int count { get; set; }
   public int c_id { get; set; }
}

Deserialize your json string into, in your case, list of MyClass.

List<MyClass> tmp = JsonConvert
    .DeserializeObject<List<MyClass>>(@"
                                        [
                                            {
                                            f_id: 100,
                                            r_id: 200,
                                            count: 2,
                                            c_id:111
                                            },
                                            {
                                            f_id: 120,
                                            r_id: 200,
                                            count: 1,
                                            c_id:111
                                            }
                                        ]
                                        ");

Access the data using index

int firstFId = tmp[0].f_id;

Update

The json string in your question is invalid.

c_id=111 

should be

c_id:111
dknaack
  • 60,192
  • 27
  • 155
  • 202