harmony json调用示例

1. book.json

假设我们手上有个json文件内容是

[
  {
    "id": 1,
    "title": "Book One",
    "author": "Author One",
    "description": "Description of Book One"
  },
  {
    "id": 2,
    "title": "Book Two",
    "author": "Author Two",
    "description": "Description of Book Two"
  }
]

创建一个 Book 实体类,定义书籍对象的结构。

// book.ets
export default class Book {
  id: number;
  title: string;
  author: string;
  description: string;

  constructor(id: number, title: string, author: string, description: string) {
    this.id = id;
    this.title = title;
    this.author = author;
    this.description = description;
  }
}

3. BookService 服务类

// book-service.ets
import Book from './book';

export default class BookService {
  getBooks(): Book[] {
    const jsonStr = this.readJSON();
    const jsonArray = JSON.parse(jsonStr);
    return jsonArray.map((item) => {
      return new Book(item.id, item.title, item.author, item.description);
    });
  }

  private readJSON(): string {
    // 使用 @Resource 读取 book.json 文件
    return AppStorage.get<string>('@app.book.json');
  }
}

4. BookListComponent 书籍列表组件

// book-list.ets
import Book from './book';
import BookService from './book-service';

@Entry
@Component
struct BookListComponent {
  @State books: Book[] = []

  build() {
    Column() {
      ForEach(this.books, (book: Book) => {
        Text(book.title).onClick(() => this.viewBookDetails(book))
      })
    }.onInit(this.fetchBooks)
  }

  fetchBooks() {
    const bookService = new BookService();
    this.books = bookService.getBooks();
  }

  viewBookDetails(book: Book) {
    router.push({
      uri: 'pages/book-detail',
      params: {
        book: book
      }
    });
  }
}

5. BookDetailComponent 书籍详情组件

// book-detail.ets
import Book from './book';

@Entry
@Component
struct BookDetailComponent {
  @State book: Book = new Book(0, '', '', '')

  build() {
    Column() {
      Text(this.book.title).fontSize(24)
      Text(this.book.author).fontSize(20)
      Text(this.book.description).fontSize(16)
    }.onInit(this.fetchBookDetails)
  }

  fetchBookDetails() {
    const book = this.$route.params.book;
    if (book) {
      this.book = book;
    }
  }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值