游戏开发一般用Lua ,媒介是C#,SDK是Java、OC,要把数据从Lua 传递到SDK 就要用数据交换。如果用特殊字符拼接,在原生平台切割这个方式会有问题,用户的名字可能就是特殊字符
关于这几种语言的json 操作
Lua
local cjson2 = require "cjson" local lua_object = { ["name"] = "Jiang", ["age"] = 24, ["addr"] = "BeiJing", ["email"] = "1569989xxxx@126.com", ["tel"] = "1569989xxxx" } local tmp = cjson2.encode(lua_object) local obj = Utils:ParseJson(tmp) print(obj["age"])
C# JsonUtility
class Person { public int age; public string name; } private void Awake(){ Person p = new Person(); p.age = 20; p.name = "zhang san"; string json = JsonUtility.ToJson(p, true); Debug.Log(json); var re = JsonUtility.FromJson<Person>(json); Debug.Log(re.age.ToString() + "-------------------"); }
//如果json的key比对象的字段多也可以正常解析
//string json = "{\"addr\": \"BeiJing\",\"tel\": \"1569989xxxx\",\"age\": 24,\"name\": \"Jiang\",\"email\": \"1569989xxxx@126.com\"}";
C# Newtonsoft.Json 上面的如果lua 加了个字段给java,在C#有使用能解析(主要是要申明一个类,其实如果需求在这里变了,改C#不能热更,策划应该能接受)
Newtonsoft是比较原始的字典,不用声明一个类
Dictionary<string, object> dic = new Dictionary<string, object>(); dic["age"] = 25; dic["name"] = "张三"; var item = JsonConvert.SerializeObject(dic); Debug.Log(item); var tmp = JsonConvert.DeserializeObject<Dictionary<string, object>>(item); Debug.Log(tmp["name"].ToString());
Java In Android import org.json.JSONObject
try{ JSONObject jsonObject1 = new JSONObject(); jsonObject1.put("name","zhangsan"); jsonObject1.put("age",12); String tmp = jsonObject1.toString(); Log.i("LogLogLog",tmp); JSONObject js2 = new JSONObject(tmp); String name = js2.getString("name"); Log.i("namenamenamename",name); } catch (Exception e) { }
Object-C In iOS
+ (NSDictionary *)dictionaryWithJsonString:(NSString *)jsonString { if (jsonString == nil) { return nil; } NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding]; NSError *err; NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&err]; if(err) { NSLog(@"json解析失败:%@",err); return nil; } return dic; }
+ (NSString *)jsonStringWithDict:(NSDictionary *)dict { NSError *error; NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:&error]; NSString *jsonString; if (!jsonData) { NSLog(@"%@",error); }else{ jsonString = [[NSString alloc]initWithData:jsonData encoding:NSUTF8StringEncoding]; } return jsonString; }
这样再也不怕用户取一些怪名字了。
更多文章请关注《万象专栏》
转载请注明出处:https://www.wanxiangsucai.com/read/cv9026