您当前的位置:首页 > 传奇技术

77M2引擎如何使用JSON命令 91M2引擎JSON脚本范例

本文出处:网游动力作者:本站发布时间:2019-05-16阅读次数:
如何使用JSON

unit Q54; 

interface
  uses Classes, SysUtils, JSON; //必须引用JSON单元

procedure Main(Npc: TNormNpc; Player: TPlayObject; Args: TArgs);

implementation

{
  TJSONValue
    TJSONObject:json对象
    TJSONNumber:数值
    TJSONTrue
    TJSONFalse
    TJSONArray:数组
}

procedure Main(Npc: TNormNpc; Player: TPlayObject; Args: TArgs);
const
  json_obj = '{"name":"77m2","version":"2014.6.8","code":100,"date":"2014-06-08","names":["白野猪","黑野猪"],"objs":[{"name":"白野猪","hp":2000},{"name":"黑野猪","hp":500}]}';       
var
  V: TJSONValue;
  O: TJSONObject; 
  A: TJSONArray; 
  I: Integer;
begin
  //从json字符串中解析json对象
  V := ParseJSONValue(json_obj);
  if V <> nil then
  begin
    try
      if V is TJSONObject then
      begin
        O := V as TJSONObject;
        Npc.MessageBox(Player, O.Values['name'].Value);  //读取name的值

        A := O.Values['objs'] as TJSONArray;
      end; 
    finally
      V.Free;
    end;
  end;   

  //直接创建JSON对象,然后写入值
  O := TJSONObject.Create;
  try
    O.AddPair('name', '77m2');  //加入字符串节点 
    O.AddPair('IsShared', True); //true  
    O.AddPair('Deleted', False); //false
    O.AddPair('Int', 100); //整型
    O.AddPair('Float', 1.25); //浮点

    A := TJSONArray.Create;  //创建一个数组对象
    A.Add('XXX');
    A.Add('AAA');
    O.AddPair('Array', A); //将数组加到json对象中,加入之后json对象会负责释放这个数组对象,所以不能手工释放被加入到其他json对象的json对象
    Npc.MessageBox(Player, O.ToString);
  finally
    O.Free; //释放json对象O,同时O会负责其内的全部json对象,比如前面加入的数组A
  end;
end;

end.


注意:JSON对象将会作为自定义消息传输的格式