Use JSON format for data exchange in unity3d

Source: Internet
Author: User
In this example, we do two things:

1. Read a JSON data from the PHP program on the server and display the content.
2. convert a Data Structure to JSON and send it to the server.

This is an example of data exchange.

First, write a simple PHP program to generate JSON data.

Named test. php.

Java code
 
  1. <? PHP
  2. $ Arr = array (
  3. 'Username' => 'foo ',
  4. 'Password' => 'bar'
  5. );
  6. Echo json_encode ($ ARR );
  7. ?>
<? PHP $ arr = array ('username' => 'foo', 'Password' => 'bar'); echo json_encode ($ ARR);?>

This program is to display the $ arr array into JSON format data. PhP5 and above support json_encode. If PhP4 requires an additional support program, you can go to json.org to find it.

The second PHP program is to convert the JSON data from unity3d post to an array. The name is test1.php, which is also very simple.

Java code
 
  1. <? PHP
  2. $ Jsonstring = $ _ post ["jsonstring"];
  3. $ Jsondata = json_decode (stripslashes ($ jsonstring), true );
  4. Echo $ jsondata ["password"];
  5. ?>
<? PHP $ jsonstring = $ _ post ["jsonstring"]; $ jsondata = json_decode (stripslashes ($ jsonstring), true); echo $ jsondata ["password"];?>

How to use it in unity? It's not hard. The following is the code. You can give whatever name you like. My name is jsontest. js.

Java code
 
  1. VaR jsonurl = "http: // localhost/JSON/test. php ";
  2. VaR jsonurl1 = "http: // localhost/JSON/test1.php ";
  3. Function start (){
  4. // Method for obtaining JSON data
  5. VaR getwww: www = new WWW (jsonurl );
  6. Yield getwww;
  7. VaR jsonobj1 = eval (getwww. data );
  8. Print (jsonobj1 ["username"]);
  9. // Method for submitting JSON data
  10. VaR mydata = new boo. Lang. Hash ();
  11. Mydata ["username"] = "hello ";
  12. Mydata ["password"] = "world ";
  13. // Convert data to a JSON string
  14. VaR jsonstring = tojson (mydata );
  15. VaR form = new wwwform ();
  16. Form. addfield ("jsonstring", jsonstring );
  17. VaR postwww: www = new WWW (jsonurl1, form );
  18. Yield postwww;
  19. Print (postwww. data );
  20. }
  21. /**
  22. * JSON Conversion
  23. */
  24. Static function tojson (OBJ ){
  25. If (OBJ = NULL) Return "null ";
  26. VaR Results = new array ();
  27. For (VAR property in OBJ ){
  28. Results. Push ("\" "+ property. Key +" \ ": \" "+ property. Value + "\"");
  29. }
  30. Return "{" + results. Join (",") + "}";
  31. }
VaR jsonurl = "http: // localhost/JSON/test. PHP "; var jsonurl1 =" http: // localhost/JSON/test1.php "; function start () {// method for obtaining JSON data var getwww: WWW = new WWW (jsonurl); yield getwww; var jsonobj1 = eval (getwww. data); print (jsonobj1 ["username"]); // Method for submitting JSON data var mydata = new boo. lang. hash (); mydata ["username"] = "hello"; mydata ["password"] = "world "; // convert data to JSON string var jsonstring = tojson (mydata); var form = new wwwform (); form. addfield ("jsonstring", jsonstring); var postwww: www = new WWW (jsonurl1, form); yield postwww; print (postwww. data);}/*** convert JSON */static function tojson (OBJ) {If (OBJ = NULL) Return "null"; var Results = new array (); for (VAR property in OBJ) {results. push ("\" "+ property. key + "\": \ "" + property. value + "\" ");} return" {"+ results. join (",") + "}";}

In start (), convert JSON into Boo directly using eval. lang. in the hash format, retrieve the username. If you look at the console, foo is displayed, that is, $ arr ['username'] in PHP. Next, submit a username and password, which are hello and world. Then, the PHP feedback is displayed, and the world is displayed on the console.

The tojson () function is a simple function written by me, that is, the boo. lang. the hash array is converted into a JSON string and can only process one-dimensional arrays. If you are interested, you can modify it to support multi-dimensional arrays.

In this way, I used to use JSON data transmission. It would be much easier if I was familiar with using JSON format, we recommend that you study this simple and convenient format to improve program efficiency.

Er, the discuz code mode cannot be used for forums in safari... The Code tag can only be edited in Firefox ...... In addition, the tojson function does not support multi-dimensional arrays because it does not know how to express undefined in ECMA Javascript in unity3d...

We still do not set the reply. We can see that some people hold personal places, some flowers hold a flower field, and some points hold a sub-field ...... =. = |

To pass Chinese characters normally in JSON, refer to this post:
Http://web3d.5d6d.com/thread-2217-1-1.html

Basically, you can transfer Chinese Characters in JSON.

Refer to this post for the JSON method in U3D:
Http://bbs.vrsh.cn/thread-2095-1-1.html

In this example, the problem is that, if the data you transmit carries Chinese characters to U3D
VaR jsonobj1 = eval (getwww. data );
This step will cause errors. The reason is that unity3d does not support \ U escape, while the json_encode function directly converts Chinese to \ u1234 when encode is used.

In fact, it is a good solution. Before echo, convert the escape string to Chinese. Unity3d is not a browser. You should directly read the binary data when calling WWW, so there is no error.

I copied the js_unescape function ...... Simple change

Java code
 
  1. <? PHP
  2. $ Arr = array (
  3. 'Username' => 'test ',
  4. 'Password' => 'bar'
  5. );
  6. Echo js_unescape (json_encode ($ ARR ));
  7. Function js_unescape ($ Str)
  8. {
  9. $ Ret = '';
  10. $ Len = strlen ($ Str );
  11. For ($ I = 0; $ I <$ Len; $ I ++)
  12. {
  13. If ($ STR [$ I] = '\' & $ STR [$ I + 1] = 'U ')
  14. {
  15. $ Val = hexdec (substr ($ STR, $ I + 2, 4 ));
  16. If ($ Val <0x7f) $ ret. = CHR ($ Val );
  17. Else if ($ Val <0x800) $ ret. = CHR (0xc0 | ($ Val> 6). CHR (0x80 | ($ Val & 0x3f ));
  18. Else $ ret. = CHR (0xe0 | ($ Val> 12 )). CHR (0x80 | ($ Val> 6) & 0x3f )). CHR (0x80 | ($ Val & 0x3f ));
  19. $ I + = 5;
  20. }
  21. Else $ ret. = $ STR [$ I];
  22. }
  23. Return $ ret;
  24. }
  25. ?>
<? PHP $ arr = array ('username' => 'test', 'Password' => 'bar'); echo js_unescape (json_encode ($ ARR )); function js_unescape ($ Str) {$ ret = ''; $ Len = strlen ($ Str); For ($ I = 0; $ I <$ Len; $ I ++) {if ($ STR [$ I] = '\' & $ STR [$ I + 1] = 'U ') {$ val = hexdec (substr ($ STR, $ I + 2, 4); If ($ Val <0x7f) $ ret. = CHR ($ Val); else if ($ Val <0x800) $ ret. = CHR (0xc0 | ($ Val> 6 )). CHR (0x80 | ($ Val & 0x3f); else $ ret. = CHR (0xe 0 | ($ Val> 12 )). CHR (0x80 | ($ Val> 6) & 0x3f )). CHR (0x80 | ($ Val & 0x3f); $ I + = 5;} else $ ret. = $ STR [$ I];} return $ ret;}?>

Java code
 

  1. VaR jsonurl = "http: // localhost/JSON/demo. php ";
  2. VaR show;
  3. VaR chineseskin: guiskin;
  4. Function start (){
  5. // Method for obtaining JSON data
  6. VaR getwww: www = new WWW (jsonurl );
  7. Yield getwww;
  8. Print (getwww. data );
  9. VaR jsonobj1 = eval (getwww. data );
  10. Print (jsonobj1 ["username"]);
  11. Show = jsonobj1 ["username"];
  12. }
  13. Function ongui (){
  14. Gui. Skin = chineseskin;
  15. Gui. Button (rect (10, 10,), show );
  16. }
VaR jsonurl = "http: // localhost/JSON/demo. PHP "; var show; var chineseskin: guiskin; function start () {// method for obtaining JSON data var getwww: www = new WWW (jsonurl); yield getwww; print (getwww. data); var jsonobj1 = eval (getwww. data); print (jsonobj1 ["username"]); show = jsonobj1 ["username"];} function ongui () {GUI. skin = chineseskin; GUI. button (rect (10, 10,), show );}

A font is required to display Chinese characters. In addition, note that the encoding of. php files should be set to UTF-8, And the encoding of U3D JS files should also be set to utf8.

=====

In addition, the JSON method linked above is also effective for the tree structure:

For example

Java code
 
  1. $ Arr = array (
  2. 'Username' => 'hao ',
  3. 'Password' => 'bar ',
  4. 'A' => array (
  5. "Name" => "AAA ",
  6. "Pass" => "BBB"
  7. )
  8. );
$ Arr = array ('username' => 'hao', 'Password' => 'bar', 'A' => array ("name" => "AAA ", "Pass" => "BBB "));

Displayed

Java code
 
  1. Print (jsonobj1 ["A"] ["name"]);
Print (jsonobj1 ["A"] ["name"]);

You will see AAA display, so the group says

For example, the database query result contains three records, each containing the name, gender, and age. Can this JSON be obtained and then returned to U3D?

Yes, you can. Forget XML. However, at present, the code uploaded from U3D to the Web does not implement a JSON tree structure, and only one layer can be passed. This can also be implemented through modification.

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.