将本地的json文件转换成java对象

这篇博客介绍了如何通过GSON库将本地的JSON文件转换为Java对象。首先,需要下载GSON的jar包,接着创建与JSON属性对应的JavaBean类,最后提供了工具类的代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.首先下载GSON 的jar 包 。如gson-2.2.4.jar


2.然后 创建一个javabean 和json里面的属性对应

3.下面是工具类代码

package myUtil;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.List;


import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import test.WSWSVoucher;


public class JsonToJava {
	   
	
	 public static void main(String[] args) throws IOException {
		 String readJsonData = readJsonData("C://新建文本文档(4).txt");
		 Gson gson = new Gson();
		 TypeToken<List<WSWSVoucher>> typeToken = new TypeToken<List<WSWSVoucher>>(){};
		 List<WSWSVoucher> wswsVoucher =(List<WSWSVoucher>)gson.fromJson(readJsonData, typeToken.getType());
	     /* WSWSVoucher fromJson = gson.fromJson
在Android中,你可以使用`java.io`包下的`FileInputStream`和`BufferedReader`,以及`org.json`库(如果还没有的话需要引入它)来读取本地JSON文件并将其换为String类型。以下是基本步骤: 1. **添加依赖**: 首先确保在build.gradle(Module: app)中添加了json库: ```groovy implementation 'com.squareup.okhttp3:okhttp:4.x.x' annotationProcessor 'com.squareup.moshi:moshi-compiler:1.x.x' ``` 2. **获取文件路径**: 获取存储在设备内部存储或者外部存储的JSON文件路径。 3. **读取文件**: ```java File file = new File(filePath); FileInputStream fis = null; BufferedReader br = null; StringBuilder sb = new StringBuilder(); try { fis = new FileInputStream(file); br = new BufferedReader(new InputStreamReader(fis)); String line; while ((line = br.readLine()) != null) { sb.append(line); sb.append('\n'); } } catch (IOException e) { // 处理异常 } finally { if (br != null) { try { br.close(); } catch (IOException e) { e.printStackTrace(); } } if (fis != null) { try { fis.close(); } catch (IOException e) { e.printStackTrace(); } } } String jsonString = sb.toString(); // 现在字符串变量里就是JSON内容 ``` 4. **解析JSON**: 使用Moshi、Gson或其他JSON解析库将字符串换为Java对象,例如一个JavaBean或POJO。 ```java JSONObject jsonObject = new JSONObject(jsonString); // 如果是JSONObject // 或者,如果是Jackson库 ObjectMapper mapper = new ObjectMapper(); YourJsonObject yourObject = mapper.readValue(jsonString, YourJsonObject.class); ```
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值