Json的应用实例——cad 二次开发c#
以下是一个使用AutoCAD C#.NET API实现你需求的示例代码,代码实现了提示用户选择一个实体,将一些字符串变量及其对应的值组成JSON格式数据存储到实体的扩展数据(XData)中,并在弹出窗口中显示该实体的所有扩展数据信息。
效果如下:
using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.DatabaseServices;
using Autodesk.AutoCAD.EditorInput;
using Autodesk.AutoCAD.Runtime;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
public class AcadXDataSample
{
[Autodesk.AutoCAD.Runtime.CommandMethod("xx")]
public void Josn设置XDATA()
{
Document doc = Application.DocumentManager.MdiActiveDocument;
Database db = doc.Database;
Editor ed = doc.Editor;
// 提示用户选择一个实体
PromptEntityOptions promptEntityOptions = new PromptEntityOptions("\n请选择一个实体: ");
PromptEntityResult promptEntityResult = ed.GetEntity(promptEntityOptions);
if (promptEntityResult.Status != PromptStatus.OK)
{
return;
}
// 定义数据键值对
Dictionary<string, string> dataDict = new Dictionary<string, string>
{
{ "权利人", "XX公司" },
{ "性质", "集体" },
{ "面积", "100㎡" },
{ "联系电话", "66-6666" }
};
string jsonData = JsonConvert.SerializeObject(dataDict);
string regAppName = "[土地登记卡]";
// 注册应用程序名称(保持不变)
using (Transaction trans = db.TransactionManager.StartTransaction())
{
RegAppTable regAppTable = trans.GetObject(db.RegAppTableId, OpenMode.ForRead) as RegAppTable;
if (!regAppTable.Has(regAppName))
{
regAppTable.UpgradeOpen();
RegAppTableRecord regAppRecord = new RegAppTableRecord();
regAppRecord.Name = regAppName;
regAppTable.Add(regAppRecord);
trans.AddNewlyCreatedDBObject(regAppRecord, true);
}
trans.Commit();
}
// 写入XData
using (Transaction trans = db.TransactionManager.StartTransaction())
{
try
{
Entity entity = trans.GetObject(promptEntityResult.ObjectId, OpenMode.ForWrite) as Entity;
if (entity != null && !entity.IsErased && entity.IsWriteEnabled)
{
ResultBuffer rb = new ResultBuffer(
new TypedValue((int)DxfCode.ExtendedDataRegAppName, regAppName), // 组码1001
new TypedValue((int)DxfCode.ExtendedDataAsciiString, jsonData) // 组码1000
);
entity.XData = rb;
trans.Commit();
ed.WriteMessage("\n扩展数据已成功写入实体。");
}
else
{
MessageBox.Show("实体不可写或已被删除。");
trans.Abort();
}
}
catch (Exception ex)
{
trans.Abort();
MessageBox.Show($"存储扩展数据时出错: {ex.Message}");
}
}
}
[CommandMethod("xxx")]
public void 显示XDATA()
{
Document doc = Application.DocumentManager.MdiActiveDocument;
Database db = doc.Database;
Editor ed = doc.Editor;
PromptEntityOptions promptEntityOptions = new PromptEntityOptions("\n请选择一个实体: ");
PromptEntityResult promptEntityResult = ed.GetEntity(promptEntityOptions);
if (promptEntityResult.Status != PromptStatus.OK) return;
using (Transaction trans = db.TransactionManager.StartTransaction())
{
try
{
Entity entity = trans.GetObject(promptEntityResult.ObjectId, OpenMode.ForRead) as Entity;
if (entity != null && entity.XData != null)
{
StringBuilder sb = new StringBuilder();
//sb.AppendLine("实体的扩展数据信息:");
foreach (TypedValue tv in entity.XData)
{
// 处理(组码不是1000)的扩展数据
if (tv.TypeCode != (int)DxfCode.ExtendedDataAsciiString)
{
sb.AppendLine($"{tv.Value}\n");
//sb.AppendLine($"类型码: {tv.TypeCode}, 原始值: {tv.Value}");
}
// 仅针对 ASCII 字符串(组码1000)尝试解析JSON
if (tv.TypeCode == (int)DxfCode.ExtendedDataAsciiString)
{
//sb.AppendLine($"类型码: {tv.TypeCode}");
string stringValue = tv.Value.ToString();
// 尝试解析JSON
bool isJson = false;
try
{
var dict = JsonConvert.DeserializeObject<Dictionary<string, string>>(stringValue);
if (dict != null && dict.Count > 0)
{
isJson = true;
//sb.AppendLine("解析为JSON:");
foreach (var item in dict)
{
sb.AppendLine($"{item.Key}:{item.Value}");
}
}
}
catch { /* 忽略解析错误 */ }
// 非JSON的纯文本直接显示
if (!isJson)
{
sb.AppendLine("文本内容:");
sb.AppendLine($" {stringValue}");
}
}
}
// 显示结果
string result = sb.ToString();
MessageBox.Show(result, "实体扩展数据信息");
ed.WriteMessage("\n" + result);
}
trans.Commit();
}
catch (Exception ex)
{
trans.Abort();
string errorMsg = $"读取扩展数据时出错: {ex.Message}";
MessageBox.Show(errorMsg);
ed.WriteMessage("\n" + errorMsg);
}
}
}
[CommandMethod("scxx")]
public void 删除XDATA()
{
}
[CommandMethod("scsy")]
public void 删除所有XDATA()
{
}
}