几个JSON在AutoCAD二次开发中应用比较有优势的场景及具体案例
场景一:存储复杂的实体属性数据
当需要存储一个实体的多个属性,且这些属性可能包含嵌套结构时,使用JSON可以方便地组织和管理这些数据。例如,存储一个建筑构件的详细信息,包括名称、尺寸、材质等。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.DatabaseServices;
using Autodesk.AutoCAD.EditorInput;
using Newtonsoft.Json; // 需要引入Newtonsoft.Json库
namespace AcadJsonExample
{
// 定义一个表示建筑构件的类
public class BuildingComponent
{
public string Name { get; set; }
public double Length { get; set; }
public double Width { get; set; }
public double Height { get; set; }
public string Material { get; set; }
}
public class JsonSample
{
[Autodesk.AutoCAD.Runtime.CommandMethod("StoreComponentData")]
public void StoreComponentData()
{
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;
}
// 创建一个建筑构件实例并设置属性
BuildingComponent component = new BuildingComponent
{
Name = "Wall",
Length = 5.0,
Width = 0.2,
Height = 3.0,
Material = "Brick"
};
// 将建筑构件实例序列化为JSON字符串
string jsonData = JsonConvert.SerializeObject(component);
// 将JSON字符串存储为实体的扩展数据(XData)
using (Transaction trans = db.TransactionManager.StartTransaction())
{
try
{
Entity entity = trans.GetObject(promptEntityResult.ObjectId, OpenMode.ForWrite) as Entity;
if (entity != null)
{
// 创建扩展数据的头部
ResultBuffer rb = new ResultBuffer(
new TypedValue((int)DxfCode.ExtendedDataRegAppName, "ComponentDataApp"),
new TypedValue((int)DxfCode.Text, jsonData)
);
entity.XData = rb;
trans.Commit();
}
}
catch (Exception ex)
{
trans.Abort();
MessageBox.Show($"存储扩展数据时出错: {ex.Message}");
}
}
}
}
}
场景二:配置文件的读取
在AutoCAD插件开发中,可能需要从配置文件中读取一些参数或设置。JSON格式的配置文件易于编写和修改,且可以方便地反序列化为对象进行使用。
using System;
using System.IO;
using System.Windows.Forms;
using Newtonsoft.Json;
namespace AcadJsonConfigExample
{
// 定义配置类
public class AcadPluginConfig
{
public string DefaultLayerName { get; set; }
public double DefaultLineWidth { get; set; }
public bool EnableAutoSave { get; set; }
}
public class JsonConfigSample
{
public static void LoadConfig()
{
try
{
string configFilePath = @"C:\AcadPlugin\config.json"; // 假设配置文件路径
if (File.Exists(configFilePath))
{
string json = File.ReadAllText(configFilePath);
AcadPluginConfig config = JsonConvert.DeserializeObject<AcadPluginConfig>(json);
// 使用配置参数,例如输出配置信息
MessageBox.Show($"默认图层名: {config.DefaultLayerName}\n" +
$"默认线宽: {config.DefaultLineWidth}\n" +
$"是否启用自动保存: {config.EnableAutoSave}");
}
else
{
MessageBox.Show("配置文件不存在。");
}
}
catch (Exception ex)
{
MessageBox.Show($"读取配置文件时出错: {ex.Message}");
}
}
}
}
以上两个案例展示了JSON在AutoCAD二次开发中存储复杂数据和读取配置文件方面的应用,通过JSON的序列化和反序列化操作,可以方便地处理各种数据结构。