java.lang.noclassdeffounderror的错误解决(关于JSONArray和JSONObject的使用)

本文详细介绍了在Java中将字符串转换为JSON数组并利用JSONArray进行操作的方法,包括必需的依赖库引入、具体应用示例以及JSONArray与JSONObject的区别。通过实例演示,帮助开发者解决实际开发中遇到的问题。

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

今天我想把一个字符串类型转换为JSON数组格式,但总是报java.lang.noclassdeffounderror的错误,最终我把这个问题解决了,下面说一下解决的步骤

一、首先是的引包

要想程序进行必须引入json-lib  jar 包,引入这个是不够的,必须引入以下的其他包

1、commons-beanutils.jar

2、commons-collections-3.2.jar

3、commons-lang-2.5.jar

4、commons-logging-1.1.1.jar

5、ezmorph-1.0.4.jar

6、json-lib-2.4-jdk15.jar

引入这些包才能保证缩写代码的正常运行

二、具体的应用(JSONArray的运用)

package zyj.com;

import java.util.List;
import net.sf.json.JSONArray;

public class JsonTest {
	public static void main(String[] args) {
		JSONArray jsonObject = JSONArray.fromObject("[{'name':'huangbiao','age':15},{'name':'liumei','age':14}]");
		List<StudentPo> student=jsonObject.toList(jsonObject,StudentPo.class);
		for (StudentPo studentPo : student) {
			System.out.println(studentPo.getName()+";"+studentPo.getAge());
		}
	}
}
结果:
huangbiao;15
liumei;14
三、JSONArray和JSONObject的区别

JSONObject是一个{}包裹起来的一个对象;

JSONArray是用[ ]包裹起来的数组;



package BeiKe; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FSDataInputStream; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapreduce.*; import org.apache.hadoop.mapreduce.lib.input.FileInputFormat; import org.apache.hadoop.mapreduce.lib.input.FileSplit; import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat; import org.json.JSONArray; import org.json.JSONObject; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.List; public class CleanHouse1 { // 自定义InputFormat处理完整JSON数组 public static class WholeFileInputFormat extends FileInputFormat<Text, Text> { @Override public RecordReader<Text, Text> createRecordReader(InputSplit split, TaskAttemptContext context) { return new WholeFileRecordReader(); } @Override protected boolean isSplitable(JobContext context, Path file) { return false; // 禁止文件分割 } } // 自定义RecordReader读取整个文件 public static class WholeFileRecordReader extends RecordReader<Text, Text> { private Text key = new Text(); private Text value = new Text(); private boolean processed = false; @Override public void initialize(InputSplit split, TaskAttemptContext context) throws IOException { FileSplit fileSplit = (FileSplit) split; Path path = fileSplit.getPath(); FileSystem fs = path.getFileSystem(context.getConfiguration()); try (FSDataInputStream in = fs.open(path); BufferedReader reader = new BufferedReader(new InputStreamReader(in))) { StringBuilder sb = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { sb.append(line); } value.set(sb.toString()); } } @Override public boolean nextKeyValue() { if (!processed) { key.set("json_array"); processed = true; return true; } return false; } @Override public Text getCurrentKey() { return key; } @Override public Text getCurrentValue() { return value; } @Override public float getProgress() { return processed ? 1.0f : 0.0f; } @Override public void close() {} } // Mapper类处理JSON数组 public static class JsonMapper extends Mapper<Text, Text, Text, Text> { // 检查是否包含无效值 private boolean containsNullValue(JSONObject json) { for (String key : json.keySet()) { Object value = json.get(key); if (value instanceof String) { String strValue = (String) value; if ("无".equals(strValue) || "暂无信息".equals(strValue)) { return true; } } } return false; } // 处理无效值 private void processNull(JSONObject json) { // 首先检查并过滤单价字段 String price = json.optString("单价(元/平方米)", ""); if (price.isEmpty() || "暂无信息".equals(price) || "无".equals(price) || "NaN".equals(price)) { return; // 直接返回,跳过此记录 } // 重命名字段 json.put("元/平方米", json.remove("单价(元/平方米)")); // 然后检查其他字段是否包含无效值 if (containsNullValue(json)) { return; // 包含无效值,跳过此记录 } } @Override protected void map(Text key, Text value, Context context) throws IOException, InterruptedException { try { String jsonString = value.toString().trim(); JSONArray jsonArray = new JSONArray(jsonString); for (int i = 0; i < jsonArray.length(); i++) { JSONObject json = jsonArray.getJSONObject(i); // 创建原始副本用于错误处理 JSONObject originalJson = new JSONObject(json.toString()); // 处理无效值 processNull(json); // 如果处理后json为空或包含无效值,则跳过 if (json.length() == 0 || containsNullValue(json)) { continue; } // 输出有效记录 - 使用固定键确保所有数据进入同一个Reducer context.write(new Text("all_records"), new Text(json.toString())); } } catch (Exception e) { System.err.println("JSON处理错误: " + e.getMessage()); System.err.println("错误数据: " + value.toString()); } } } // Reducer类构建完整JSON数组 public static class JsonReducer extends Reducer<Text, Text, Text, Text> { @Override protected void reduce(Text key, Iterable<Text> values, Context context) throws IOException, InterruptedException { // 收集所有JSON对象 List<JSONObject> jsonObjects = new ArrayList<>(); for (Text value : values) { jsonObjects.add(new JSONObject(value.toString())); } // 构建完整JSON数组 StringBuilder result = new StringBuilder("[\n"); for (int i = 0; i < jsonObjects.size(); i++) { // 格式化JSON对象输出 JSONObject obj = jsonObjects.get(i); result.append(" {\n"); // 添加每个字段并格式化 String[] keys = obj.keySet().toArray(new String[0]); for (int j = 0; j < keys.length; j++) { String field = keys[j]; result.append(" \"").append(field).append("\": "); Object val = obj.get(field); if (val instanceof String) { result.append("\"").append(val).append("\""); } else { result.append(val); } if (j < keys.length - 1) { result.append(","); } result.append("\n"); } result.append(" }"); if (i < jsonObjects.size() - 1) { result.append(","); } result.append("\n"); } result.append("]"); // 输出完整JSON数组 context.write(null, new Text(result.toString())); } } public static void main(String[] args) throws Exception { Configuration conf = new Configuration(); Job job = Job.getInstance(conf, "JSON Array Processor"); job.setJarByClass(CleanHouse.class); job.setInputFormatClass(WholeFileInputFormat.class); job.setMapperClass(JsonMapper.class); job.setReducerClass(JsonReducer.class); job.setOutputKeyClass(Text.class); job.setOutputValueClass(Text.class); FileInputFormat.addInputPath(job, new Path(args[0])); FileOutputFormat.setOutputPath(job, new Path(args[1])); System.exit(job.waitForCompletion(true) ? 0 : 1); } }上述代码运行结果如下[root@hadoop01 software]# hadoop jar CleanHouse2.jar /out1/part-r-00000 /out2 Exception in thread "main" java.lang.NoClassDefFoundError: BeiKe/CleanHouse at BeiKe.CleanHouse1.main(CleanHouse1.java:205) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:498) at org.apache.hadoop.util.RunJar.run(RunJar.java:221) at org.apache.hadoop.util.RunJar.main(RunJar.java:136) Caused by: java.lang.ClassNotFoundException: BeiKe.CleanHouse at java.net.URLClassLoader.findClass(URLClassLoader.java:381) at java.lang.ClassLoader.loadClass(ClassLoader.java:424) at java.lang.ClassLoader.loadClass(ClassLoader.java:357) ... 7 more
06-14
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值