Flutter JSON-LD处理插件json_ld_processor的使用

Flutter JSON-LD处理插件json_ld_processor的使用

此包实现了JSON-LD处理算法1.1URDNA2015规范化算法 在纯 Dart 中。

重要提示: 此包尚在开发中。并非所有算法都已实现,并且某些功能可能无法完美运行(参见实现状态)。但总体上来说,它已经可以使用了。

使用

Map<String, dynamic> input = {}; // 有效的 Json-ld 文档
// 扩展
var expanded = await JsonLdProcessor.expand(input);
// 扁平化
var flattened = await JsonLdProcessor.flatten(input);
// 转换为 RDF
var rdf = await JsonLdProcessor.toRdf(input);
// 规范化(URDNA2015)并添加选项
var normalized = await JsonLdProcessor.normalize(input, options: JsonLdOptions(safeMode: true));

SafeMode 选项

正如在 Java 实现的规范化算法 URDNA2015 和 URGNA2012 中所示 (在其仓库中),在使用 JSON-LD 和规范化进行签名时存在一些安全漏洞。在某些情况下,文档可能会被篡改,而签名仍然有效。其中一个原因在于扩展算法。如果输入文档中的属性不能扩展为 IRI 或关键字,则该属性将被丢弃而不包含在规范化数据集中。为了在这种情况下抛出异常,有一个 safeMode 选项,默认设置为 false。但如果设置为 true,则会抛出异常。如果不这样做,属性将按标准方式丢弃。我建议在对 JSON-LD 文档进行规范化处理后再签名时将其设置为 true

注意: 引入此选项的想法来自于 JavaScript 实现,该实现也支持 JSON-LD Playground。此选项目前尚未成为标准的一部分。

实现状态和测试覆盖率

算法 测试通过 测试失败 备注
扩展 363 8
扁平化 55 1 一个失败,因为缺少压缩算法
压缩 94 149 需要修复错误
fromRdf 0 0 尚未实现
toRdf 406 30 rdfDirection 选项尚未实现
规范化 62 1

运行测试

测试数据来自 此处 的 json-ld api 测试和 此处 的规范化测试。因此,如果你想运行这些测试,需要克隆这两个仓库到本地。

未来计划

  • 修复错误
  • 实现压缩和 fromRdf
  • 支持 框架

示例代码

import 'package:json_ld_processor/json_ld_processor.dart';

void main() async {
  print(RdfDataset.fromNQuad(
      '_:c14n0 <ex:foo> "{\"@context\":\"ex:not:a:context\",\"test\":1}"^^<http://www.w3.org/1999/02/22-rdf-syntax-ns#JSON> .'));
  var exampleData = {
    "@context": [
      "https://www.w3.org/2018/credentials/v1",
      {
        'familyName': {'@id': 'http://family.org'},
        'givenName': {'@id': 'http://family.org'}
      }
    ],
    "id": "credential:000-4892",
    "issuer": 'did:example:1364723',
    "issuanceDate":
        '${DateTime.now().toUtc().toIso8601String().split('.').first}Z',
    "credentialSubject": {
      "id": 'did:example:8344648190',
      "givenName": "Max",
      "familyName": "Mustermann"
    },
    "type": ["VerifiableCredential"]
  };

// 扩展
  var expanded = await JsonLdProcessor.expand(exampleData);
  print('expanded:\n$expanded \n\n');
// 扁平化
  var flattened = await JsonLdProcessor.flatten(exampleData);
  print('flattened:\n$flattened \n\n');
// 转换为 RDF
  var rdf = await JsonLdProcessor.toRdf(exampleData);
  print('as rdf:\n$rdf \n\n');
// 规范化
  var normalized = await JsonLdProcessor.normalize(exampleData,
      options: JsonLdOptions(safeMode: true));
  print('normalized:\n$normalized \n\n');

  // 规范化 RDF 数据集
  var nquadString =
      '''<credential:000-4892> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <https://www.w3.org/2018/credentials#VerifiableCredential> .
<credential:000-4892> <https://www.w3.org/2018/credentials#credentialSubject> <did:example:8344648190> .
<credential:000-4892> <https://www.w3.org/2018/credentials#issuanceDate> "2022-09-22T17:40:19Z"^^<http://www.w3.org/2001/XMLSchema#dateTime> .
<credential:000-4892> <https://www.w3.org/2018/credentials#issuer> <did:example:1364723> .
<did:example:8344648190> <http://family.org> "Max" .
<did:example:8344648190> <http://family.org> "Mustermann" . 
''';

  var asDataset = RdfDataset.fromNQuad(nquadString);
  var normalized2 = await JsonLdProcessor.normalize(asDataset);
  print('normalized2:\n$normalized2 \n\n');
}

更多关于Flutter JSON-LD处理插件json_ld_processor的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter JSON-LD处理插件json_ld_processor的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


当然,下面是一个关于如何在Flutter项目中使用json_ld_processor插件来处理JSON-LD(JSON for Linked Data)的示例代码。这个插件允许你解析、序列化和操作JSON-LD数据。

首先,确保你已经在pubspec.yaml文件中添加了json_ld_processor依赖:

dependencies:
  flutter:
    sdk: flutter
  json_ld_processor: ^最新版本号  # 请替换为实际的最新版本号

然后,运行flutter pub get来获取依赖。

接下来,你可以在你的Flutter项目中使用这个插件。以下是一个完整的示例,展示如何解析和序列化JSON-LD数据。

import 'package:flutter/material.dart';
import 'package:json_ld_processor/json_ld_processor.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter JSON-LD Processor Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: Scaffold(
        appBar: AppBar(
          title: Text('Flutter JSON-LD Processor Demo'),
        ),
        body: Center(
          child: JsonLdDemo(),
        ),
      ),
    );
  }
}

class JsonLdDemo extends StatefulWidget {
  @override
  _JsonLdDemoState createState() => _JsonLdDemoState();
}

class _JsonLdDemoState extends State<JsonLdDemo> {
  String? parsedJsonLdOutput;

  @override
  void initState() {
    super.initState();
    _processJsonLd();
  }

  Future<void> _processJsonLd() async {
    // 示例JSON-LD数据
    String jsonLdString = '''
    {
      "@context": {
        "@vocab": "http://schema.org/",
        "name": "name",
        "homepage": { "@id": "homepage", "@type": "@id" }
      },
      "@type": "Person",
      "name": "John Doe",
      "homepage": "http://johndoe.com"
    }
    ''';

    // 解析JSON-LD
    Map<String, dynamic> jsonLdMap = jsonDecode(jsonLdString);
    try {
      // 使用json_ld_processor解析
      ExpandedDocument expandedDoc = await JsonLdProcessor.expand(jsonLdMap);
      print('Expanded JSON-LD: $expandedDoc');

      // 序列化回紧凑格式(可选)
      CompactedDocument compactedDoc = await JsonLdProcessor.compact(
        expandedDoc,
        context: jsonDecode('{"@vocab": "http://schema.org/"}'),
      );
      print('Compacted JSON-LD: $compactedDoc');

      // 设置状态以显示输出
      setState(() {
        parsedJsonLdOutput = jsonEncode(compactedDoc);
      });
    } catch (e) {
      print('Error processing JSON-LD: $e');
    }
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      mainAxisAlignment: MainAxisAlignment.center,
      children: <Widget>[
        Text('Original JSON-LD (String format):'),
        SizedBox(height: 10),
        Text('''
        {
          "@context": {
            "@vocab": "http://schema.org/",
            "name": "name",
            "homepage": { "@id": "homepage", "@type": "@id" }
          },
          "@type": "Person",
          "name": "John Doe",
          "homepage": "http://johndoe.com"
        }
        ''', style: TextStyle(fontSize: 14),),
        SizedBox(height: 20),
        Text('Processed JSON-LD (Compact format):'),
        SizedBox(height: 10),
        Text(parsedJsonLdOutput ?? 'Loading...', style: TextStyle(fontSize: 14),),
      ],
    );
  }
}

在这个示例中,我们:

  1. pubspec.yaml中添加了json_ld_processor依赖。
  2. 创建了一个Flutter应用,并在其中添加了一个页面JsonLdDemo
  3. JsonLdDemoinitState方法中,我们定义了一个示例JSON-LD字符串。
  4. 使用json_ld_processor插件的expandcompact方法来处理这个JSON-LD数据。
  5. 将处理后的JSON-LD数据(紧凑格式)显示在UI上。

请注意,json_ld_processor插件的API可能会随着版本的更新而变化,因此请查阅最新的文档以获取最新的使用方法和API。

回到顶部