How to convert json objects?

Source: Internet
Author: User
The json format is as follows:
{"LoginResult": {"code": "005", "teamId": "1", "password": "123", "role": "employee ", "roleId": "2 "}}

The CI framework I used defines a Member_Model object in models. the attributes include code, teamId, password, role, and roleId.
How to convert the preceding JSON data into an object and assign it to Member_Model


Reply to discussion (solution)

$ Json = '{"loginResult": {"code": "005", "teamId": "1", "password": "123", "role ": "employee", "roleId": "2"} '; $ arr = json_decode ($ json); $ mm = new Member_Model (); foreach ($ arr-> loginResult as $ key => $ value) {$ mm-> $ key = $ value ;}

$ S = '{"loginResult": {"code": "005", "teamId": "1", "password": "123", "role ": "employee", "roleId": "2"} '; $ o = json_decode ($ s); print_r ($ o-> loginResult );

I don't know about the ci framework.

Do you have to use foreach for traversing? is there any other method? can you directly convert json into an object like C # and assign values directly.

This is because the data order in the json data is known. if the data order in the json data is unknown, how can we know which element of the array is assigned to the corresponding attribute. In this case, you have to judge the key in foreach before assigning values. this is too much trouble. The returned json is just a separate object. if it is an object list, it is not more troublesome. Is there a simpler way to find a simpler solution.

$ O-> isn't loginResult the object you want?

$ O-> loginResult error
Trying to get property of non-object

Paste your code to see




$ Buffer is a json string

You have $ result = json_decode ($ buffer, true );
$ Result is already an array
You can access $ member = $ result-> LoginResult as an object;
Are you sure you want to avoid mistakes?

What should I do?

If yes
$ Result = json_decode ($ buffer, true );
Then
$ Member = $ result ['loginresult'];

If yes
$ Result = json_decode ($ buffer );
Then
$ Member = $ result-> loginResult;

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.