I need to create a .json.gz file using an ArrayList
void func(ArrayList<AirConfig> configList)
{
String filePath = "abc.json.gz";
File file = new File(filePath);
ObjectMapper mapper = new ObjectMapper();
mapper.writeValue(file, configList);
}
This however dosent really work because when I try to unzip the file using the following command
gzip -cd configMasterAirport_Test.json.gz > configMasterAirport_Test.json
I get the following error,
abc.json.gz: not in gzip format
How do I rewrite my code so that the a compressed json is generated but I'm still able to use the Object Mapper
You require only a small change.
void func(ArrayList<AirConfig> configList)
{
FileOutputStream fStream = null;
GZIPOutputStream zStream = null;
try
{
String filePath = "abc.json.gz";
fStream = new FileOutputStream(filePath);
zStream = new GZIPOutputStream(new BufferedOutputStream(fStream));
ObjectMapper mapper = new ObjectMapper();
mapper.writeValue(zStream, configList);
}
finally
{
if (zStream != null)
{
zStream.flush();
zStream.close();
}
if (fStream != null)
{
fStream.flush();
fStream.close();
}
}
}
Related
I would like to work on moving the json data from libgdx to my web server, but I am not sure how to do it. The method below was created by referring to libgdx's documentation.
private void httpPostJson(){
final Json json = new Json();
final String requestJson = json.toJson(requestObject);
Net.HttpRequest request = new Net.HttpRequest("POST");
final String url = "http://localhost:8080/data";
request.setUrl(url);
request.setContent(requestJson);
request.setHeader("Content-Type", "application/json");
Gdx.net.sendHttpRequest(request, new Net.HttpResponseListener() {
#Override
public void handleHttpResponse(Net.HttpResponse httpResponse) {
String responseJson = httpResponse.getResultAsString();
Gson gson = new Gson();
data = gson.fromJson(responseJson, Person.class);
//'Person' is just sample class. data is class Person's object.
data.StoreData("",1);//successed to receive json data from web server.
//StoreData is just getter method.
}
#Override
public void failed(Throwable t) {
Gdx.app.log("failed!");
}
#Override
public void cancelled() {
Gdx.app.log("cancelled!");
}
});
}
It is possible to receive data transmitted from a web server.
But, this method can't send data to web server.
Can you tell me how to move data from libgdx project to web server?
This is the data transmitted to the web server:
final String requestJson = json.toJson(requestObject);
We are using the following Code (as you have more control over the request as opposed to using gdx.net), works like a charm, just don't execute on the main thread - body is your JSON as String
URL url = new URL(<your url>);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setRequestProperty("Accept", "application/json");
conn.setRequestProperty("Content-Type",
"application/json; charset=utf-8");
if (body != null) {
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(
os, "UTF-8"));
writer.write(body);
writer.close();
os.close();
}
conn.connect();
String s = stringFromStream(conn.getInputStream(), 4096);
Method stringFromStream:
public static String stringFromStream(final InputStream is,
final int bufferSize) {
final char[] buffer = new char[bufferSize];
final StringBuilder out = new StringBuilder();
try {
final Reader in = new InputStreamReader(is, "UTF-8");
try {
for (; ; ) {
int rsz = in.read(buffer, 0, buffer.length);
if (rsz < 0)
break;
out.append(buffer, 0, rsz);
}
} finally {
in.close();
}
} catch (Exception ex) {
}
return out.toString();
}
How to test Json with Xunit, I currently have a method that will read and collect .json information, I would like to do tests simulating any return, null and valid returns.
I wanted to test this code:
public class BLLParametros
{
public static INFOParametros CarregarParametros()
{
INFOParametros parametros = new INFOParametros();
string startupPath = Environment.CurrentDirectory;
if (System.IO.File.Exists(startupPath + #"\parametros.json"))
{
// deserialize JSON directly from a file
using (StreamReader file = File.OpenText(startupPath + #"\parametros.json"))
{
JsonSerializer serializer = new JsonSerializer();
parametros = (INFOParametros)serializer.Deserialize(file, typeof(INFOParametros));
}
}
else
{
return null;
}
return parametros;
}
}
I am trying to append a row at the end of my csv file using the code below
public class Register {
public static void add(int k,int m,int id1) throws Exception
{
ClassLoader classLoader = Register.class.getClassLoader();
try{
FileWriter fw = new FileWriter(new File(classLoader.getResource("data/dataset.csv").getFile()),true);
BufferedWriter bw = new BufferedWriter(fw);
bw.append("\n");
bw.append(String.valueOf(id1));
bw.append(',');
bw.append(String.valueOf(m));
bw.append(',');
bw.append(String.valueOf(k));
bw.close();
}catch(IOException ioe){
System.out.println("Exception occurred:");
ioe.printStackTrace();
}
}
}
I am calling this class from a servlet using a loop as I need to add 5 lines to my csv. Everything runs fine, but nothing gets added to the csv file. Please help.
You need to close the FileWriter object to flush the content into the file as shown below:
FileWriter fw = null;
BufferedWriter bw = null;
try{
fw = new FileWriter(new File(classLoader.
getResource("data/dataset.csv").getFile()),true);
bw = new BufferedWriter(fw);
bw.append("\n");
bw.append(String.valueOf(id1));
bw.append(',');
bw.append(String.valueOf(m));
bw.append(',');
bw.append(String.valueOf(k));
bw.close();
}catch(IOException ioe){
System.out.println("Exception occurred:");
ioe.printStackTrace();
} finally {
if(bw != null) {
bw.close();
}
if(fw != null) {
fw.close();
}
}
As a side note, ensure that you are closing the resources (like the writer objects above) inside the finally block (which you are not doing).
Given some list of objects:
List<Car> carlist = new List<Car>();
How can I serialize this list as an XML or binary file and deserialize it back?
I have this so far but it doesn't work.
//IsolatedStorageFile isFile = IsolatedStorageFile.GetUserStoreForApplication();
//IsolatedStorageFileStream ifs = new IsolatedStorageFileStream("myxml.xml", FileMode.Create,isFile);
//DataContractSerializer ser = new DataContractSerializer();
//XmlWriter writer = XmlWriter.Create(ifs);
//ser.WriteObject(writer, carlist);
I'm using these methods to Save and Load from a XML file in/to the IsolatedStorage :
public static class IsolatedStorageOperations
{
public static async Task Save<T>(this T obj, string file)
{
await Task.Run(() =>
{
IsolatedStorageFile storage = IsolatedStorageFile.GetUserStoreForApplication();
IsolatedStorageFileStream stream = null;
try
{
stream = storage.CreateFile(file);
XmlSerializer serializer = new XmlSerializer(typeof (T));
serializer.Serialize(stream, obj);
}
catch (Exception)
{
}
finally
{
if (stream != null)
{
stream.Close();
stream.Dispose();
}
}
});
}
public static async Task<T> Load<T>(string file)
{
IsolatedStorageFile storage = IsolatedStorageFile.GetUserStoreForApplication();
T obj = Activator.CreateInstance<T>();
if (storage.FileExists(file))
{
IsolatedStorageFileStream stream = null;
try
{
stream = storage.OpenFile(file, FileMode.Open);
XmlSerializer serializer = new XmlSerializer(typeof (T));
obj = (T) serializer.Deserialize(stream);
}
catch (Exception)
{
}
finally
{
if (stream != null)
{
stream.Close();
stream.Dispose();
}
}
return obj;
}
await obj.Save(file);
return obj;
}
}
You can customize the error handling in the catch().
Also, you can adjust the Load method to your needs, in my case I am trying to load from a file and if doesn't exist, it creates a default one and puts the default serialized object of the type provided according to the constructor.
UPDATE :
Let's say you have that list of cars :
List< Car > carlist= new List< Car >();
To save, you can just call them as await carlist.Save("myXML.xml"); , as it is an asynchronous Task(async).
To load, var MyCars = await IsolatedStorageOperations.Load< List< Car> >("myXML.xml"). (I think, I haven't used it like this, as a List so far...
DataContactJsonSerializer performs better than XmlSerializer. It creates smaller files and handles well lists inside properties.
sorry for the silly question, but i am stuck converting for example the following result from a method into Json
public string Test(string input) {
return "Name:" + input;
}
to look like this
{"Name":"Mike"}
Update:
Darin fixed first problem now i am using this way but it is not working
StringBuilder sb = new StringBuilder();
StringWriter sw = new StringWriter(sb);
using(JsonWriter jsonWriter = new JsonTextWriter(sw)) {
jsonWriter.Formatting = Formatting.Indented;
jsonWriter.WritePropertyName("Name");
jsonWriter.WriteValue("Mike");
}
I get
'{"Name":{"m_MaxCapacity":2147483647,"Capacity":16,"m_StringValue":"\\"Name\\": \\"Mike\\"","m_currentThread":0}}';
You could use the JavaScriptSerializer class:
public string Test(string input)
{
var serializer = new JavaScriptSerializer();
return serializer.Serialize(new { Name = input });
}
Example usage:
string json = Test("Mike"); // json = {"Name":"Mike"}
UPDATE:
Didn't notice you wanted a solution using the Json.NET library. Here's one:
string json = JsonConvert.SerializeObject(new { Name = input });