VS2017配置C#使用json格式

配置环境

用户可通过 socket 通讯向控制器控制端口 8055 发送指定格式的 json 字符串来实现相关sdk 功能。

VS软件配置

1.鼠标右键点击方案名

2.选择管理 NuGet 包管理器

3.在浏览选项输入 json,安装第一个插件包 Newtonsoft.Json

4.添加引用,在方案引用选项点击鼠标右键选中添加

5.在搜索框输入 Serialization,勾选第一个 using System.Runtime.Serialization 点击确定

添加引用

using:对命名空间的引用

添加引用

Examples

Example 1

using Newtonsoft.Json;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.Runtime.Serialization;
using System.Text;
namespace json_Csharp
{
    class Program
    {
        static void Main(string[] args)
        {
            String IP = "192.168.1.200";
            int port = 8055;
            Json.connectETController(IP, port);
            //获取机器人状态
            Json.Json_str getState = Json.SendCMD("getRobotState");
            if (getState.result.ToString() == "4")
            {
                //清除报警
                Json.Json_str clearAlarm = Json.SendCMD("clearAlarm");
            }
            Json.Json_str getMotorStatus = Json.SendCMD("getMotorStatus");
            if (getMotorStatus.result.ToString() == "false")
            {
                //同步编码器数据
                Json.Json_str set_servo_status = Json.SendCMD("syncMotorStatus");
            }
            //获取机器人位姿
            Json.Json_str getpose = Json.SendCMD("getRobotPose");
            Console.WriteLine("getpose:{0}", string.Join(",", getpose.robot_array));
            //获取机器人位置
            Json.Json_str getpos = Json.SendCMD("getRobotPos");
            Console.WriteLine("getpos:{0}", string.Join(",", getpos.robot_array));
        }
    }
    [DataContract]
class Json
    {
public static Socket ClientSocket;
[DataMember]
public string jsonrpc { get; set; }
[DataMember]
public string method { get; set; }
[DataMember]
public object param { get; set; }
[DataMember]
public int id { get; set; }
[DataMember]
public object error { get; set; }
[DataMember]
public object result { get; set; }
[DataMember]
public double[] robot_array { get; set; }
public static bool connectETController(string IP, int port)
{
try
{
IPAddress ip = IPAddress.Parse(IP); //将 IP 地址字符串转换成 IPAddress
实例
ClientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stre
am, ProtocolType.Tcp);//使用指定的地址簇协议、套接字类型和通信协议
IPEndPoint endPoint = new IPEndPoint(ip, port); // 用指定的 ip 和端口号
初始化 IPEndPoint 实例
ClientSocket.Connect(endPoint); //与远程主机建立连接
return true;
}
catch (Exception ex)
{
Console.WriteLine(ex);
return false;
throw;
}
}
public static Json_str SendCMD(string cmd, object param = null)
{
Json_str descJson = null;
    ArrayList d_array = new ArrayList();
string rec = "";
try
{
List<Json> send_json = new List<Json>(){
new Json(){jsonrpc="2.0",method=cmd,param=param,id=1 } };
string jsonData = JsonConvert.SerializeObject(send_json);
jsonData = jsonData.Substring(1, jsonData.Length - 2);
jsonData = jsonData.Replace("param", "params");
jsonData = jsonData.Replace("null", "[]");
jsonData += "\n";
byte[] message = Encoding.ASCII.GetBytes(jsonData); //通信时实际发送
的是字节数组,所以要将发送消息转换字节
ClientSocket.Send(message);//发送 byte 数组
byte[] receive = new byte[1024];//定义接收长度
int length = ClientSocket.Receive(receive); // length 接收字节数组长
度
rec = Encoding.ASCII.GetString(receive);
descJson = JsonConvert.DeserializeObject<Json_str>(rec);
if (descJson.result != null && descJson.result.ToString().IndexOf("["
) != -1)
{
string ret_string = descJson.result.ToString().Substring(descJson
.result.ToString().IndexOf("["), descJson.result.ToString().LastIndexOf("]"));
ret_string = ret_string.Replace("[", "");
ret_string = ret_string.Replace("]", "");
string[] s = ret_string.Split(',');
for (int i1 = 0; i1 < s.Length; i1++)
{
d_array.Add(Double.Parse(s[i1]));
}
descJson.robot_array = (double[])d_array.ToArray(typeof(double));
}
return descJson;
}
catch (Exception ex)
{
Console.Write(ex);
descJson = null;
return descJson;
}
}
public class Json_str
{
[DataMember]
    public string jsonrpc { get; set; }
[DataMember]
public object error { get; set; }
[DataMember]
public object result { get; set; }
[DataMember]
public int id { get; set; }
[DataMember]
public double[] robot_array { get; set; }
         }
    }
}   

Example 2

using Newtonsoft.Json;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.Runtime.Serialization;
using System.Text;
namespace json_Csharp
{
class Program
{
static void Main(string[] args)
{
String IP = "192.168.1.200";
int port = 8055;
Json.connectETController(IP, port);
//获取机器人状态
Json.Json_str getState = Json.SendCMD("getRobotState");
if ((string)getState.result == "4")
{
//清除报警
Json.Json_str clearAlarm = Json.SendCMD("clearAlarm");
    }
Json.Json_str getMotorStatus = Json.SendCMD("getMotorStatus");
if ((string)getMotorStatus.result == "false")
{
//同步编码器数据
Json.Json_str set_servo_status = Json.SendCMD("syncMotorStatus");
}
double[] ready = { -90,-90,90,-90,90,-90,0,0};
Json.Json_str move_J = Json.SendCMD("moveByJoint", new { targetPos =
ready, speed = 20, acc = 50, dec = 50 });
//获取机器人状态
getState = Json.SendCMD("getRobotState");
while ((string)getState.result!="0")
{
getState = Json.SendCMD("getRobotState");
}
//获取机器人位姿
Json.Json_str getpose = Json.SendCMD("getRobotPose");
Console.WriteLine("getpose:{0}", string.Join(",", getpose.robot_array
));
double[] run_pose = getpose.robot_array;
run_pose[0] = run_pose[0] + 100;
Json.Json_str run_pos = Json.SendCMD("inverseKinematic", new { target
Pose = run_pose });
Json.Json_str move_L = Json.SendCMD("moveByLine", new { targetPos = r
un_pos.robot_array, speed=100, acc=50,dec=50 });
//获取机器人状态
getState = Json.SendCMD("getRobotState");
while ((string)getState.result != "0")
{
getState = Json.SendCMD("getRobotState");
}
}
}
[DataContract]
class Json
{
public static Socket ClientSocket;
[DataMember]
public string jsonrpc { get; set; }
[DataMember]
public string method { get; set; }
[DataMember]
    public object param { get; set; }
[DataMember]
public int id { get; set; }
[DataMember]
public object error { get; set; }
[DataMember]
public object result { get; set; }
[DataMember]
public double[] robot_array { get; set; }
public static bool connectETController(string IP, int port)
{
try
{
IPAddress ip = IPAddress.Parse(IP); //将 IP 地址字符串转换成
IPAddress 实例
ClientSocket = new Socket(AddressFamily.InterNetwork, SocketType.
Stream, ProtocolType.Tcp);//使用指定的地址簇协议、套接字类型和通信协议
IPEndPoint endPoint = new IPEndPoint(ip, port); // 用指定的 ip 和端
口号初始化 IPEndPoint 实例
ClientSocket.Connect(endPoint); //与远程主机建立连接
return true;
}
catch (Exception ex)
{
Console.WriteLine(ex);
return false;
throw;
}
}
public static Json_str SendCMD(string cmd, object param = null)
{
Json_str descJson = null;
ArrayList d_array = new ArrayList();
string rec = "";
try
{
List<Json> send_json = new List<Json>(){
new Json(){jsonrpc="2.0",method=cmd,param=param,id=1 } };
string jsonData = JsonConvert.SerializeObject(send_json);
jsonData = jsonData.Substring(1, jsonData.Length - 2);
jsonData = jsonData.Replace("param", "params");
    jsonData = jsonData.Replace("null", "[]");
jsonData += "\n";
byte[] message = Encoding.ASCII.GetBytes(jsonData); //通信时实际
发送的是字节数组,所以要将发送消息转换字节
ClientSocket.Send(message);//发送 byte 数组
byte[] receive = new byte[1024];//定义接收长度
int length = ClientSocket.Receive(receive); // length 接收字节数
组长度
rec = Encoding.ASCII.GetString(receive);
descJson = JsonConvert.DeserializeObject<Json_str>(rec);
if (descJson.result != null && descJson.result.ToString().IndexOf
("[") != -1)
{
string ret_string = descJson.result.ToString().Substring(desc
Json.result.ToString().IndexOf("["), descJson.result.ToString().LastIndexOf("]"))
;
ret_string = ret_string.Replace("[", "");
ret_string = ret_string.Replace("]", "");
string[] s = ret_string.Split(',');
for (int i1 = 0; i1 < s.Length; i1++)
{
d_array.Add(Double.Parse(s[i1]));
}
descJson.robot_array = (double[])d_array.ToArray(typeof(doubl
e));
}
return descJson;
}
catch (Exception ex)
{
Console.Write(ex);
descJson = null;
return descJson;
}
}
public class Json_str
{
[DataMember]
public string jsonrpc { get; set; }
[DataMember]
public object error { get; set; }
[DataMember]
public object result { get; set; }
    [DataMember]
public int id { get; set; }
[DataMember]
public double[] robot_array { get; set; }
}
}
}
       
点击显示全文
赞同0
发表评论
分享

手机扫码分享
0
1.031K
收藏
举报
收起
登录
  • 密码登录
  • 验证码登录
还没有账号,立即注册
还没有账号,立即注册
注册
已有账号,立即登录
选择发帖板块
上传文件
举报
请选择举报理由
举报
举报说明