If our JSON data consists only of flat, one-dimensional data,
how can convert those data by iterating over your outer objects and building a CSV line by concating the string values of your inner objects.
Could anyone provide with example please?
You can try this :
import org.json.CDL;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class toCSV {
public static void main(String args[]){
String jsonString = "{\"infile\": [{\"field1\": 11,\"field2\": 12,\"field3\": 13},{\"field1\": 21,\"field2\": 22,\"field3\": 23},{\"field1\": 31,\"field2\": 32,\"field3\": 33}]}"
JSONObject output = new JSONObject(jsonString);
JSONArray docs = response.getJSONArray("infile");
File file=new File("C:/JsontoCSVExample.csv");
String csv = CDL.toString(docs);
FileUtils.writeStringToFile(file, csv);
}
}
The maven dependency was like,
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20090211</version>
</dependency>
Also, You can take ref. from here
Related
import java.io.*;
import java.util.*;
import com.fasterxml.jackson.databind.MappingIterator;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.dataformat.csv.CsvMapper;
import com.fasterxml.jackson.dataformat.csv.CsvSchema;
import com.fasterxml.jackson.databind.MappingIterator.*;
public class CsvtoJson {
public static void main(String args[]) throws Exception {
File input = new File("input.csv");
try {
CsvSchema csv = CsvSchema.emptySchema().withHeader();
CsvMapper csvMapper = new CsvMapper();
MappingIterator<Map<?, ?>> mappingIterator = csvMapper.reader().forType(Map.class).with(csv).readValues(input);
List<Map<?, ?>> list = mappingIterator.readAll();
System.out.println(list);
} catch(Exception e) {
e.printStackTrace();
}
}
}
Compilation Error:-
The method forType(Class) is undefined for the type ObjectReader
The method readAll() is undefined for the type MappingIterator<Map>
Trying to convert a big CSV file into JSON with Jackson library but I am stuck with this error. All jars all correctly added in the build path.
The code works fine for me (JDK13), I think you have dependency problem. Please make sure you have jars for these dependencies(versions are not much important):
com.fasterxml.jackson.core:jackson-annotations:2.11.1
com.fasterxml.jackson.core:jackson-core:2.11.1
com.fasterxml.jackson.core:jackson-databind:2.11.1
com.fasterxml.jackson.dataformat:jackson-dataformat-csv:2.11.1
Note: It is much easy to create a maven project with an IDE. When you create a maven project add this dependecy to your maven pom file.
<dependency>
<groupId>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-csv</artifactId>
<version>2.11.1</version>
</dependency>
I have an array of jsons like this
[
{"submitted":"Bob","limit":0,"ID":123,"target":3},
{"submitted":"Kate","limit":500,"ID":3221,"target":2}
]
I need to find a way how to insert a record into that file, without overwriting the file, or loading everything into memory
currently i'm doing it like this
try (FileWriter file = new FileWriter("C:/test/output.json", true);
BufferedWriter bfile = new BufferedWriter(file);
PrintWriter outFile = new PrintWriter(bfile))
{
outFile.write(obj.toJSONString()+System.lineSeparator());
outFile.flush();
}
catch (IOException e) {
e.printStackTrace();
}
You can read and write json object&array using org.json as below. But I can't sure that editing a json file without reading it into memory could be possible.
package yourPackage;
import org.json.JSONArray;
import org.json.JSONObject;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
public class Main {
public static void main(String[] args) throws IOException {
JSONArray root = new JSONArray(new String(Files.readAllBytes(Paths.get("test.json"))));
JSONObject obj = new JSONObject();
obj.put("submitted","");
obj.put("limit", 0);
obj.put("ID", 123);
obj.put("target", 3);
root.put(obj);
Files.write(Paths.get("test.json"), root.toString().getBytes());
}
}
maven dependency of org.json :
<!-- https://mvnrepository.com/artifact/org.json/json -->
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20180130</version>
</dependency>
I'm trying to convert JSON into XML. But I'm getting an error that org.json cannot be resolved. I have also imported the external jar file java-json.jar. Below is my java code:
import org.json.JSONObject;
public class JsontoXML{
public static void main(String args[])
{
String str ={'name':'JSON','integer':1,'double':2.0,'boolean':true,'nested' {'id':42},'array':[1,2,3]}";
JSONObject json = new JSONObject(str);
String xml = XML.toString(json);
System.out.println(xml);
}
}
Your application is alright. You need to have a well formed JSON object.
Source Code
package algorithms;
import org.json.JSONObject;
import org.json.XML;
public class JsonToXML{
public static void main(String args[])
{
JSONObject json = new JSONObject("{name: JSON, integer: 1, double: 2.0, boolean: true, nested: { id: 42 }, array: [1, 2, 3]}");
String xml = XML.toString(json);
System.out.println(xml);
}
}
Check with the example above.
Output:
<boolean>true</boolean><array>1</array><array>2</array><array>3</array><double>2.0</double><name>JSON</name><integer>1</integer><nested><id>42</id></nested>
Your issue is related to jar. You need to import the org.json package for the XML methods to work.
if you are using maven try:
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20140107</version>
</dependency>
Or else download the jar from this maven repo and add to your library.
Underscore-java can convert json to xml:
String json = "{\"name\":\"JSON\",\"integer\":1,\"double\":2.0,\"boolean\":true,\"nested\": {\"id\":42},"
+ "\"array\":[1,2,3]}";
String xml = U.jsonToXml(json);
System.out.println(xml);
output:
<?xml version="1.0" encoding="UTF-8"?>
<root>
<name>JSON</name>
<integer number="true">1</integer>
<double number="true">2.0</double>
<boolean boolean="true">true</boolean>
<nested>
<id number="true">42</id>
</nested>
<array number="true">1</array>
<array number="true">2</array>
<array number="true">3</array>
</root>
I have read the posts that appeared to be the same as my question but I must be missing something. My environment is Eclipse Mars. My JAVA is 1.7 and I have imported json-simple. I simply wish to parse the json that is returned from my web service. I control the web service if I need to modify its output. I see the json in arg[0] as noted below however the Object obj is null as of course is the JSONArray array. I know that I am missing something basic but I am stumped and a bit tired.
Here is the returned json:
[{"$id":"1","NumberID":121183,"PortfolioID":718,"PropertyID":14489,"Adsource":17287,"PlanTypeID":1,"GreetingFile":"HolidayGreeting.wav","PromptFile1":"senior.leasing.first.wav","Accepts1":2,"PromptAction_ID1":1,"PromptFile2":"Default.wav","Accepts2":2,"PromptAction_ID2":1,"PromptFile3":"Default.wav","Accepts3":2,"PromptAction_ID3":1,"PromptFile4":"Default.wav","Accepts4":2,"PromptAction_ID4":1,"PromptFile5":"Default.wav","Accepts5":2,"PromptAction_ID5":1,"HoldMsgFile1":"SpectrumHold.wav","HoldMsgFile2":"Default.wav","Destination1":15197,"Destination2":15024,"Destination3":0,"UIType_ID":16,"RingCount":0,"Enabled":true,"Spanish":false,"HoldMusicFile":"Hold_Music.wav","Template_ID":41,"FrontLineForward":true,"DisclaimerFIle":"1Silence.wav"}]
Here is the parse code employing json-simple:
package parser;
import org.json.simple.*;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import java.io.*;
public class JsonParser
{
private static JSONObject _jsonInput;
public static void main(String[] args)
{
//TODO
try{
JSONParser parser = new JSONParser();
Object obj = JSONValue.parse(args[0]);
JSONArray array=(JSONArray)obj;
String name = array.get(3).toString();
System.out.println(obj);
}
catch(Exception e){
e.printStackTrace();
}
}
}
The size of the array different than the index used
JSONParser parser = new JSONParser();
Object obj = parser.parse(new FileReader(args[1]));
JSONArray array=(JSONArray)obj;
if (array.size() > 3)
String name = array.get(3).toString();
I'm trying to get the Metadata Values from an Office Document and all it shows as key-value pair is this one:
Content-Type: application/zip
I just can't tell the issue in this one. Why does it only show the Content-Type?
What i'm interested in are Keys like title.
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import org.apache.tika.exception.TikaException;
import org.apache.tika.metadata.Metadata;
import org.apache.tika.parser.AutoDetectParser;
import org.apache.tika.sax.BodyContentHandler;
import org.xml.sax.SAXException;
public class App
{
private static final String PATH = "C:/docs/myDocument.docx";
public static void main( String[] args ) throws IOException, SAXException, TikaException
{
Metadata metadata = new Metadata();
AutoDetectParser parser = new AutoDetectParser();
InputStream fileStream = new FileInputStream(PATH);
BodyContentHandler handler = new BodyContentHandler();
parser.parse(fileStream, handler, metadata);
String[] metadataNames = metadata.names();
for (String key : metadataNames) {
String value = metadata.get(key);
System.out.println(key + ": " + value);
}
}
}
Promoting a comment to an answer - you appear to be missing some key Apache Tika jars or their dependencies.
If you're using Maven, then your pom should have (as of January 2015) should have something like:
<properties>
<tika.version>1.7</tika.version>
</properties>
<dependencies>
<dependency>
<groupId>org.apache.tika</groupId>
<artifactId>tika-core</artifactId>
<version>${tika.version}</version>
</dependency>
<dependency>
<groupId>org.apache.tika</groupId>
<artifactId>tika-parsers</artifactId>
<version>${tika.version}</version>
</dependency>
</dependencies>
The tika-core artifact gives you everything you need to run Tika, and develop your own parsers, but doesn't come with any parsers. It's the tika-parsers artifact (+dependencies!) which provides all the built-in Tika parsers, which you need to process files liek yours