How to convert IPentahoResultSet to JSON object - java

I am writing java code trying to convert an IPentahoResultSet to JSON so I can send it to a server using apache commons httpclient. I could not find any way to convert this pentaho result set to JSON. Any help will be appreciated.
I have tried this code to serialize it, but it does not work. I think it is meant to serialize classes not resultsets.
import flexjson.JSONSerializer;
import org.pentaho.commons.connection.marshal.MarshallableResultSet;
.
.
.
IPentahoResultSet data;
//data will contain result of executing and MDX against Mondrian
MarshallableResultSet result = new MarshallableResultSet();
result.setResultSet(data);
JSONSerializer serializer = new JSONSerializer();
String json = serializer.deepSerialize( result );

Related

How to print org.hibernate.query.criteria.internal.CriteriaQueryImp to String in Java

I am trying to print the query for logging purpose, I tried using ObjectMapper to convert org.hibernate.query.criteria.internal.Criteria object into String but getting serialisation error.
Any suggestion would be helpful..
Thanks
If you just want to convert the object to String , you can try GSON. You have to install the Gson jar first after that
String query = new Gson().toJson(hibernate_object);

Get JSON into Apache Spark from a web source in Java

I have a web server which returns JSON data that I would like to load into an Apache Spark DataFrame. Right now I have a shell script that uses wget to write the JSON data to file and then runs a Java program that looks something like this:
DataFrame df = sqlContext.read().json("example.json");
I have looked at the Apache Spark documentation and there doesn't seem a way to automatically join these two steps together. There must be a way of requesting JSON data in Java, storing it as an object and then converting it to a DataFrame, but I haven't been able to figure it out. Can anyone help?
You could store JSON data into a list of Strings like:
final String JSON_STR0 = "{\"name\":\"0\",\"address\":{\"city\":\"0\",\"region\":\"0\"}}";
final String JSON_STR1 = "{\"name\":\"1\",\"address\":{\"city\":\"1\",\"region\":\"1\"}}";
List<String> jsons = Arrays.asList(JSON_STR0, JSON_STR1);
where each String represents a JSON object.
Then you could transform the list to an RDD:
RDD<String> jsonRDD = sc.parallelize(jsons);
Once you've got RDD, it's easy to have DataFrame:
DataFrame data = sqlContext.read().json(jsonRDD);

Looking for a less verbose way to parse JSON in Android (Java)

I'm writing an app that uses JSON (from a Kimonolabs API) and while I was able to utilize my API effortlessly in Python as such:
results = json.loads(urllib.request.urlopen(KimonoAPIlink).read().decode('utf-8'))
Which returns a useable JSON dictionary:
title = results['results']['suart'][0]['stitle']['text']
href = results['results']['suart'][0]['stitle']['href']
In Java (Android specifically) I have to do it this way (Using Gson):
URL url = new URL(KimonoAPIlink);
HttpURLConnection request = (HttpURLConnection) url.openConnection();
request.connect();
JsonParser jp = new JsonParser(); //from gson
JsonElement root = jp.parse(new InputStreamReader((InputStream) request.getContent()));
JsonObject rootobj = root.getAsJsonObject(); //May be an array, may be an object.
JsonElement x = rootobj.getAsJsonObject("results").getAsJsonArray("suart").get(0);
JsonObject y = x.getAsJsonObject();
title.setText(y.getAsJsonObject("stitle").getAsJsonPrimitive("text").toString().replace("\"", "").replace("\\","\""));
Is there any way to do this that isn't so verbose and complicated? (my code works, I'd just like it to be more simple and clean)
Moreover, can I somehow parse the whole nested JSON object into something useful (like python does) and not reparse it each layer I access?
Thanks in advance.
Edit: I've also seen people use Apache commons.io on here for this, but I don't think it returns a different JSON object (i.e. I'd still have to parse every layer)
Check out GSON, Jackson or Moshi
What you are looking for is lookup using JsonPath, wherein JSON coordinates are represented by a string with syntax pretty similar to the one you are using in Python (as well as other featuress).
For example, in your case it would be $.results.suart[o].stitle.text.
A quick look in the docs and the gson github shows it is not implemented in gson, although the JsonReader class does support a method to return that value.
There is a library implementation JsonPath in java (called JsonPath). Here's a one line code for your case (ignoring connection detail):
String result = JsonPath.parse("[some json]").read("$.results.suart[o].stitle.text");

Parse json received from webservice? [duplicate]

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>

Creating BSON object from JSON string

I have Java app that takes data from external app. Incoming JSONs are in Strings. I would like to parse that Strings and create BSON objects.
Unfortunate I can't find API for that in Java's BSON implementation.
Do I have use external parser for that like GSON?
... And, since 3.0.0, you can:
import org.bson.Document;
final Document doc = new Document("myKey", "myValue");
final String jsonString = doc.toJson();
final Document doc = Document.parse(jsonString);
Official docs:
Document.parse(String)
Document.toJson()
Official MongoDB Java Driver comes with utility methods for parsing JSON to BSON and serializing BSON to JSON.
import com.mongodb.DBObject;
import com.mongodb.util.JSON;
DBObject dbObj = ... ;
String json = JSON.serialize( dbObj );
DBObject bson = ( DBObject ) JSON.parse( json );
The driver can be found here: https://mongodb.github.io/mongo-java-driver/
Use Document.parse(String json) from org.bson.Document. It returns Document object which is type of Bson.
The easiest way seems to be to use a JSON library to parse the JSON strings into a Map and then use the putAll method to put those values into a BSONObject.
This answer shows how to use Jackson to parse a JSON string into a Map.
To convert a string json to bson, do:
import org.bson.BasicBSONEncoder;
import org.bson.BSONObject;
BSONObject bson = (BSONObject)com.mongodb.util.JSON.parse(string_json);
BasicBSONEncoder encoder = new BasicBSONEncoder();
byte[] bson_byte = encoder.encode(bson);
To convert a bson to json, do:
import org.bson.BasicBSONDecoder;
import org.bson.BSONObject;
BasicBSONDecoder decoder = new BasicBSONDecoder();
BSONObject bsonObject = decoder.readObject(out);
String json_string = bsonObject.toString();
You might be interested in bson4jackson project, which allows you to use Jackson data binding to work with BSON (create POJOs from BSON, write as BSON) -- especially since Jackson also work with JSON. So it will allow conversion like you mention, just use different ObjectMapper instanstaces (one that works with JSON, other with BSON).
With Jackson you can either work with full POJOs (declare structure you want) or with simple Maps, Lists and so on. You just need to declare what to type to bind to when reading data (when writing, type is defined by object you pass).
You'll find the answer to your question in the source code of https://github.com/mongodb/mongo/blob/master/src/mongo/db/jsobj.cpp
Which has the BSON to JSON conversion.
Basically, stuff like
ObjectId("XXX") -> { "$oid" : "XXX" }
/XXX/gi -> { "$regex" : "XXX", "$options" : "gi" }
and so on...
I would suggest using the toJson() and parse(String) methods of the BasicDBObject, because the JSON utility class has been #Depricated.
import com.mongodb.BasicDBObject;
public static BasicDBObject makeBsonObject(String json) {
return BasicDBObject.parse(json);
}
public static String makeJsonObject(BasicDBObject dbObj) {
return dbObj.toJson();
}
I am not sure about java but the mongoDB CPP driver has a function type
BSONObj fromjson(string)
which returns a BSONObj according to the string passed. There should be a same function in Java too.

Categories