You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React Native JSON解析失败求助:多拼接JSON数据无法解析与展示

解决React Native解析拼接JSON数据的问题

首先得揪出核心问题:后端返回的不是合法的JSON格式。你遇到的{"id":"1"...}{"id":"2"...}这种多个JSON对象直接拼接的内容,完全不符合JSON规范——JSON要求顶级结构只能是单个对象或数组,所以response.json()解析失败是必然的,这和React Native的Text组件根本没关系哦。

接下来咱们一步步解决问题:

1. 先把非法拼接文本转换成合法JSON数组

当你换成response.text()能拿到完整拼接字符串后,我们可以手动把它转成合法的数组格式:

.then((response) => response.text())
.then((responseText) => {
  // 把}{替换成},{,再包裹成数组结构
  const validJsonText = `[${responseText.replace(/}{/g, '},{')}]`;
  const responseJson = JSON.parse(validJsonText);
  // 把处理好的数据存到组件state里
  this.setState({
    data: responseJson,
    isLoading: false
  });
})

2. 修正你的HomeScreen组件代码错误

你的组件代码里有好几处语法和逻辑问题,直接导致renderItems报undefined:

  • componentDidMount位置错误,它是类的方法,不能放在constructor内部
  • 没有把数据存在组件的state中,而是用了全局变量,导致this.data根本不存在
  • 数组遍历方法拼写错误:是forEach不是foreach
  • 数组添加元素应该用push,不是put
  • styles定义位置错误且有语法闭合问题

修正后的完整组件代码:

import React from 'react';
import { View, Text, ActivityIndicator, StyleSheet, Card } from 'react-native';

export default class HomeScreen extends React.PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      isLoading: true,
      data: [] // 初始化data为空数组
    };
  }

  componentDidMount() {
    fetch(`http://www.example.com/React/data.php`, {
      method: 'POST',
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json',
      },
    })
    .then((response) => response.text())
    .then((responseText) => {
      // 处理非法拼接的JSON文本
      const validJsonText = `[${responseText.replace(/}{/g, '},{')}]`;
      const responseJson = JSON.parse(validJsonText);
      this.setState({
        data: responseJson,
        isLoading: false
      });
    })
    .catch((error) => {
      console.warn(error);
      this.setState({ isLoading: false }); // 出错也要结束加载状态
    });
  }

  renderItems() {
    // 从state取数据,遍历生成对应组件
    return this.state.data.map((dataItem, index) => (
      <View key={index} style={{ marginVertical: 8 }}>
        <Text>ID: {dataItem.id}</Text>
        <Text>图片名: {dataItem.imagename}</Text>
      </View>
    ));
  }

  render() {
    if (this.state.isLoading) {
      return (
        <View style={{flex: 1, paddingTop: 20, justifyContent: 'center'}}>
          <ActivityIndicator size="large" />
        </View>
      );
    }

    return(
      <View style={styles.MainContainer}>
        <Card>
          <View style={{ padding: 16 }}>
            {this.renderItems()}
          </View>
        </Card>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  MainContainer: {
    flex:1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#333',
    padding: 16
  },
});

额外建议

最稳妥的解决方案其实是让后端返回合法的JSON数组,比如[{"id":"1",...},{"id":"2",...}],这样前端不需要做额外的文本处理,既可靠又符合规范。如果后端能修改的话,优先建议调整后端输出格式哦。

内容的提问来源于stack exchange,提问作者Laney Williams

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 07:17:28