Dead silence! Not often you experience that on Stackoverflow... I've added a small bounty to get things going!
I've built a json document containing information about the location of various countries. I have added some custom keys. This is the beginning of the json-file:
{
"type": "FeatureCollection",
"features": [
{ "type": "Feature", "properties": {
"NAME": "Antigua and Barbuda",
"banned/censored": "AG",
"Bombed": 29,
"LON": -61.783000, "LAT": 17.078000 },
"geometry": { "type": "MultiPolygon", "coordinates": [ [ [ [ -61.686668,...
All the custom keys (like bombed, banned/censored etc.) have values, but they are just old (bogus if you want) values. The real values are kept in a .csv file extracted from a excel document.
I e.g. have this:
banned/censored bombed
Antigua and Barbuda 2 120
...
Now I want to match these values with the proper key in the json-file. Is there any programs out there that I can use? Another option would be a json library for java, which somehow supports what I want. I havent been able to find an easy solution for it yet. The document is pretty large ~ 10MB, if it makes any difference!
EDIT: I've used QGIS to manipulate the .shp file, so some kind of extension could be of use too.
Just convert both the JSON and the CSV to a fullworthy Java object. This way you can write any Java logic to your taste to alter the Java objects depending on the one or other. Finally convert the modified Java object representing the JSON data back to a JSON string.
There is however one problem in your JSON. The / in banned/censored is not a valid character for a JSON field name, so many of the existing JSON deserializers may choke on this. If you fix this, then you'll be able to use one of them.
I can recommend using Google Gson for the converting between JSON and Java. Here's a kickoff example based on your JSON structure (with banned/censored renamed to bannedOrCensored):
class Data {
private String type;
private List<Feature> features;
}
class Feature {
private String type;
private Properties properties;
private Geometry geometry;
}
class Properties {
private String NAME;
private String bannedOrCensored;
private Integer Bombed;
private Double LON;
private Double LAT;
}
class Geometry {
private String type;
private Double[][][][] coordinates;
}
You only need to add/generate getters and setters yourself. Then, you'll be able to convert between JSON and Java like follows:
Data data = new Gson().fromJson(jsonString, Data.class);
To convert between CSV and a Java object, just pick one of the many CSV parsers, like OpenCSV. You can even homegrow your own with help of BufferedReader.
Finally, after altering the Java object representing the JSON data, you can convert it back to JSON string with help of Gson as follows:
String json = new Gson().toJson(data);
While BalusC's answer tells you how to do it in your current setup, I have a more radical suggestion: get rid of the JSON.
By idea JSON is not meant to store data - it is meant to be used as a "lightweight text-based open standard designed for human-readable data interchange". That is:
low-traffic (as little non-meaningful data as possible)
human-readable
easy to handle with dynamic languages
Data storages on the other hand have much more requirements than this. That's why databases exist. So move your storage to a database. If you don't want a full-featured database, use something like HSQLDB or JavaDB.
Related
Say, I have a json file like below:
[{
"obj1_key1":"aa",
"obj1_array":[{"e1":"11"},{"e2":"22"}]
},
{
"obj2_key1":"cc",
"obj2_key2":"dd"
}]
Now I want update the file into something like below:
[{
"obj1_key1":"aa",
"obj1_array":[{"e1":"11"},{"e2":"22"},{"e3":"333"}]
},
{
"obj2_key1":"cc",
"obj2_key2":"dd"
}]
I tried using ObjectMapper to parse the file like
JsonNode jsonFile = new ObjectMapper().readTree(new File("file.json");
however then I need to find the obj1_array and append a json object, then write the json object back to the file. And I don't think the way I load the json file as a JsonNode is a easy way because I should convert it between Json/JsonArray back and forth. So I'm wondering is there a simpler way to make this work? Really appreciate that.
if it is just a one-off case, you can use your preferred mechanism, but if it is going to used often, I would prefer
Convert the JSON to a POJO ( using some parser eg Jackson )
Update the requisite fields
Return the Json object.
I need to load a text file of information into Java. The Text file looks like this
"reproduce": {
"VB": 7
},
"drill": {
"VB": 8,
"NN": 16
},
"subgross": {
"JJ": 2
},
"campsites": {
"NNS-HL": 1,
"NNS": 1
},
"streamed": {
"VBN": 1,
"VBD": 2
}
It is basically a huge collection of words with some tags included. I need to save this information in some sort of Java data-structure so that the program can search and retrieve tag statistics for a given word.
From what I've read, using a type of HashMap would be the best idea? Something like:
Map<KeyType, List<ValueType>>
Is that a good idea? How would I go about scanning this data from the text file? I could probably find a way to print the dictionary to the text file that would be easier to scan into Java.
While your input does not look exactly like JSON, you might be able to preprocess[1] it in a simple way to make it valid JSON. Because JSON is probably much more widespread and therefore better supported than your custom format.
If your problem then is JSON deserialization, then take a look at Jackson or Gson, which will convert your input string into objects.
Simple example in Jackson:
ObjectMapper mapper = new ObjectMapper(); // can reuse, share globally
Map<String,Object> data = mapper.readValue(new File("file.json"), Map.class);
// process data further here ...
Both Jackson and Gson have a lot of options and can handle complex inputs in various ways, e.g. they can serialize and deserialize from and to Maps, custom Objects, can handle polymorphism (mapping different inputs to objects of different classes) and more.
Given the input, that is currently in your question, you can simply prepend and append a curly bracket, and you would have valid JSON:
{
"reproduce": {
"VB": 7
},
"drill": {
"VB": 8,
"NN": 16
},
"subgross": {
"JJ": 2
},
"campsites": {
"NNS-HL": 1,
"NNS": 1
},
"streamed": {
"VBN": 1,
"VBD": 2
}
}
This question already has answers here:
How do I parse JSON in Android? [duplicate]
(3 answers)
Closed 8 years ago.
I need to parse this JSON:
{
"out":{
"nroRegistros":1,
"asignaciones":[
{
"lat":"456",
"lng":"456",
"direccion":"Nocedal 108 Estacion Central",
"depto":null,
"descripcion":"Casa amplia, cerca del metro las rejas",
"tipoVehiculo":null,
"referencia":null,
"rutDenunciante":null,
"nombreDenunciante":null,
"apePaternoDenunciante":null,
"apeMaternoDenunciante":null,
"fonoMovilDenunciante":null,
"ambito":null,
"prioridad":null,
"ley":null,
"articulo":null,
"marcaVehiculo":null,
"colorVehiculo":null,
"placaPatente":null,
"id":null
}
]
},
"status":{
"code":1,
"message":"success"
}
}
From all I have read I cant find an example or something to guide me. I am new to json and i can't really find a way to make it work. I have read a lot of tutorials but they all are quite simple. I understand them but I cant make this one work.
First of all, use some json parser to visualize data, for example http://jsonviewer.stack.hu/. This will make it for you a lot easier to understand the structure of the data.
Next step is to create a model class to accept the json you are receiving. This you have to do it by yourself, in eclipse or any other IDE you might be using.
It will look something like this:
public class JsonModel{
public Object out;
public Object status;
}
here I put Object as a general type, you may want to define the variables to an appropriate type to reflect the structure of the json file.
Once you have the model, you can simply get the data by any json library, I like to use Gson 3rd party for any json work. It would be something like so:
string json = getJsonFromInternet();
JsonModel mymodel = new Gson().fromJson(json, JsonModel.class);
your data will be stored in mymodel, as Java object, which you can use according to your needs.
I hope this helps.
find Json parsing tutorials
Json Parsing good example
You can achieve this by using JsonLib.
Try to put those values in HashMap , make sure you create the same structure of pojo classes as defined in the Json String (case sensitive)
Your json will be mapped using the classMap.put method. From there on , we have a great controller over the java bean object.
Try to explore few things, before you jump into it
String json = "{'out':[{'test':'testname'},{'test2':'testname2'}]}";
Map classMap = new HashMap();
classMap.put( "out", YourClass.class );
MyBean bean = JSONObject.toBean( JSONObject.fromObject(json), MyBean.class, classMap );
Reference
<link>http://json-lib.sourceforge.net/snippets.html</link>
I have the following JSON and I'm only interested in getting the elements "status", "lat" and "lng".
Using Gson, is it possible to parse this JSON to get those values without creating the whole classes structure representing the JSON content?
JSON:
{
"result": {
"geometry": {
"location": {
"lat": 45.80355369999999,
"lng": 15.9363229
}
}
},
"status": "OK"
}
You don't need to define any new classes, you can simply use the JSON objects that come with the Gson library. Heres a simple example:
JsonParser parser = new JsonParser();
JsonObject rootObj = parser.parse(json).getAsJsonObject();
JsonObject locObj = rootObj.getAsJsonObject("result")
.getAsJsonObject("geometry").getAsJsonObject("location");
String status = rootObj.get("status").getAsString();
String lat = locObj.get("lat").getAsString();
String lng = locObj.get("lng").getAsString();
System.out.printf("Status: %s, Latitude: %s, Longitude: %s\n", status,
lat, lng);
Plain and simple. If you find yourself repeating the same code over and over, then you can create classes to simplify the mapping and eliminate repetition.
It is indeed possible, but you have to create a custom deserializer. See Gson documentation here and Gson API Javadoc here for further info. And also take a look at other reponses of mine here and here... and if you still have doubts, comment.
That said, in my opinion it is much easier for you to parse it creating the correspondent classes, even more taking into account the simplicity of your JSON response... With the usual approach you only have to write some super-simple classes, however, writing a custom deserializer, although is not that complex, it will take you probably longer, and it will be more difficult to adapt if later on you need some data else of your JSON...
Gson has a way of operating that has been designed for developers to use it, not for trying to find workarounds!
Anyway, why do you not want to use classes? If you don't like to have many classes in your project, you can just use nested classes and your project will look cleaner...
I am using org.json api to convert xml to json. The problem is certain tags in my xml contain non string values (i.e., int, boolean, double etc...).
The code I am using below, is successfully converting xml to json, but the primitive data types are converted to string in the json response. For eg: <age>10<age> in xml gets converted to {"age" : "10" } in which the value 10 in json is a String which should be an Integer. For example {"age" : 10 }.
The xml input which I give for conversion, is dynamic and will change frequently. But for the sake of showing it as an example, I am saving the xml as a String. The dynamically generated xml code will be saved in a string variable.
Can anyone help me out in converting the xml to json, while preserving the data types? Below is the code
import org.json.*;
public class XmlToJson {
private static String xmlCode =
"<handler>
<price>10</price>
<item>rice</item>
<VALUE>3434</VALUE>
</handler>
<flow>
</flow>";
public static void main(String[] args) throws JSONException{
JSONObject xmlJsonObj=null;
xmlJsonObj = XML.toJSONObject(xmlCode);
System.out.println(xmlJsonObj.toString(1));
}
}
Sample output:
{
"flow": "",
"handler": {
"VALUE": "3434",
"item": "rice",
"price": "10"
}
}
The expected behavior is:
{
"flow": "",
"handler": {
"VALUE": 3434,
"item": "rice",
"price": 10
}
}
You should have a look at my open source library unXml, which parses xml, and outputs Json. It's written for Java 8, and uses the (awesome) Jackson Json-library.
UnXml is available on Maven Central.
Given this xml (Added a root to make wellformed)
<root>
<handler>
<price>10</price>
<item>rice</item>
<VALUE>3434</VALUE>
</handler>
<flow></flow>
</root>
You create a parser like this
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.nerdforge.unxml.Parsing;
import com.nerdforge.unxml.factory.ParsingFactory;
import com.nerdforge.unxml.parsers.Parser;
import org.w3c.dom.Document;
public class XmlParser {
public ObjectNode parseXml(String inputXml){
Parsing parsing = ParsingFactory.getInstance().create();
Document document = parsing.xml().document(inputXml);
Parser<ObjectNode> parser = parsing.obj("root")
.attribute("flow")
.attribute("handler", "handler", parsing.obj()
.attribute("price", "price", parsing.number())
.attribute("item")
.attribute("value", "VALUE", parsing.with(Integer::parseInt))
)
.build();
ObjectNode result = parser.apply(document);
return result;
}
}
Which will return this Json
{
"handler":{
"item":"rice",
"price":10.0,
"value":3434
},
"flow":""
}
If your schema is set, you can go through databinding with POJOs ( convert XML into JSOs,
convert POJOs to JSON ) - there is a lot of databinding tools and I would recomment those working on top of pull-model ( XStream for XML, GSON for JSON - but there is a rich choice
to pich your favorite )
If you are better on XML side, you can also write XSLT transformation which will convert XML to whatever you like , also JSON - though I personally find JavaBeans way easier
I second Konstantin's suggestion of using POJOs in-between XML and JSON -- otherwise you will be having endless problems due to mismatch between the two. Specifically, XML has "native" way of expressing arrays/Lists, so handling of empty and single-element lists/arrays typically produces odd results.
My suggestion would be to use Jackson for JSON and either JAXB or Jackson XML-data-binding for XML -- that way you can also use JAXB annotations for extra information, if naming has to be changed or so.
And whatever else you use, dump org.json package; alternatives are better nowadays so that package serves mostly as historical relic (it was useful when alternatives weren't around).