POCO::PostgreSQL retrieve JSON datatype - json

What is the best way to retrieve data from JSON field in PostgreSQL using POCO framework?
The only way I see is:
Poco::Data::RecordSet rs(session, sql);
rs.moveFirst();
string value = rs[0].convert<std::string>(); // get JSON as string
Poco::JSON::Parser parser;
parser.parse(value);
Poco::Dynamic::Var result = parser.result();
// now we can extract Object, Array and so on
Direct extract
Poco::JSON::Object object = os[0].extract<Poco::JSON::Object>()
throws Can not convert [ERRFMT] to [ERRFMT] exception.
Any better solution?

Var result = parser.parse(value);
Object::Ptr object = result.extract<Object::Ptr>();

Related

How to convert Amazon QLDB IonStruct to Json in java?

I have written a QLDB query to fetch a document by document ID So that I want to convert this document to a JSON response and pass it through the rest end point.
qldbDriver.QldbDriver().execute(txn ->{
IonSystem ionSys = IonSystemBuilder.standard().build();
Result result = txn.execute("SELECT * FROM _ql_committed_WALLET WHERE metadata.id = ?",ionSys.newString(id));
IonStruct person = (IonStruct) result.iterator().next();
String s = person.get("data").toPrettyString();
});
Here I want that conversation.
How can I fix this issue?
There are many ways to achieve what you are trying to do. But picking up from your example, you might want to convert your result person into JSON directly, or you might want to use a library to generate that JSON. If it possible to convert from IonValue (of which IonStruct is an instance) to POJOs and then you could convert those to JSON using Jackson.
import com.fasterxml.jackson.dataformat.ion.IonObjectMapper;
import com.fasterxml.jackson.databind.ObjectMapper;
...
IonValue personValue = qldbDriver.QldbDriver().execute(txn ->{
IonSystem ionSys = IonSystemBuilder.standard().build();
Result result = txn.execute("SELECT * FROM _ql_committed_WALLET WHERE metadata.id = ?",ionSys.newString(id));
return (IonStruct) result.iterator().next();
});
Person person = IonObjectMapper.builder().build().readValue(personValue, Person.class);
String personJson = new ObjectMapper().writeValueAsString(person);
In this example we are taking the IonValue as returned from QLDB and converting it to a POJO using the Jackson Ion library. Then we use the regular JSON Jackson library to convert that same Person POJO into a JSON string which you can then send over your REST connection as the body of the response.

JSON Parse using C#

Anybody has any idea how to parse below type of JSON object where same object named objects are present in master object. Below is an example
abc{
"abc":"123"
}
How to parse the child abc value?
You can use Json.NET it is vary easy to use. Json.NET handles JSON arrays natively, and will parse them into any type, string,int etc.
Are you currently using a JSON framework? Maybe check out Json.NET: http://www.newtonsoft.com/json.
Then you could do something like:
int onetwothree = jObject.SelectToken("abc.abc");
You can use http://www.newtonsoft.com/json to parse any json string on c#:
Your example :
var jsonString= "{\"abc\":{ \"abc\":\"123\" }}";
var jObj = JObject.Parse(jsonString);
var abcValue = jObj.SelectToken("abc.abc").Value<string>();

solrj QueryResponse convert to json

I use solrj to submit a query to solr , that returns the result in json format.
SolrQuery query = new SolrQuery();
SolrQuery query = new SolrQuery();
query.setParam("kw", keyword);
query.setParam("lc", location);
query.setParam("wt", "json");
query.setParam(CommonParams.QT, "/lds");
QueryResponse qResponse = solrServer.query(query);
searchResultStr = qResponse.toString();
But the searchResultStr does not have a string in JSON format. Instead it has something like this:
{responseHeader={status=0,QTime=21},location={has_zipcode=true,location_param=94085}}
But if i directly hit the solr url in the browser, I get the correct JSBON format:
{"responseHeader":{"status":0,"QTime":15},"location": {"has_zipcode":true,"location_param":"94085"}}
For a JSON output you will have to query a HTTPSolrServer using curl as mentioned in the answer here. Using EmbeddedSolrServer will not help i.e. solrj.
When you use solrj to query you will have to get the SolrDocumentList from the QueryResponseobject and convert it into JSON format by iterating through each SolrDocument and entering the data into JSON the way you want.
Solr QueryResponse returns a hashmap, so use any hashmap to json converter to get the json out of it. Here I have used Gson() for that conversion.
QueryResponse response = solr.query(query);
Gson gson = new Gson();
String json = gson.toJson(response.getResults());
System.out.println(json);

Couchbase - deserialize json into dynamic type

I'm trying to deserialize some JSON coming back from couchbase into a dynamic type.
The document is something like this so creating a POCO for this would be overkill:
{
UsersOnline: 1
}
I figured that something like this would do the trick, but it seems to deserialize into a dynamic object with the value just being the original JSON
var jsonObj = _client.GetJson<dynamic>(storageKey);
results in:
jsonObj { "online": 0 }
Is there anyway I can get the couchbase deserializer to generate the dynamic type for me?
Cheers
The default deserializer for the client uses .NET's binary serializer, so when you save or read a JSON string, it's just a string. GetJson will always just return a string. However, there are a couple of options:
You could convert JSON records to Dictionary instances:
var appJson = "{ \"UsersOnline\" : 1, \"NewestMember\" : \"zblock\" }";
var result = client.ExecuteStore(StoreMode.Set, "userCount", appJson);
var item = client.GetJson<Dictionary<string, object>>("userCount");
Console.WriteLine("There are {0} users online. The newest member is {1}.",
item["UsersOnline"], item["NewestMember"]);
Or you could use a dynamic ExpandoObject instance:
var appJson = "{ \"UsersOnline\" : 1, \"NewestMember\" : \"zblock\" }";
var result = client.ExecuteStore(StoreMode.Set, "userCount", appJson);
dynamic item = client.GetJson<ExpandoObject>("userCount");
Console.WriteLine("There are {0} users online. The newest member is {1}.",
item.UsersOnline, item.NewestMember);
In either case you're losing static type checking, which seems like it's OK for your purposes. In both cases you get access to the JSON properties without having to parse the JSON into a POCO though...
Edit: I wrote a couple of extension methods that may be useful and blogged about them at http://blog.couchbase.com/moving-no-schema-stack-c-and-dynamic-types

difference between json string and parsed json string

what is the difference between json string and parsed json string?
for eg in javascript suppose i have a string in the json format say [{},{}]
parsing this string will also produce the same thing.
So why do we need to parse?
It's just serialization/deserialization.
In Javscript code you normally work with the object, as that lets you easily get its properties, etc, while a JSON string doesn't do you much good.
var jsonobj = { "arr": [ 5, 2 ], "str": "foo" };
console.log(jsonobj.arr[1] + jsonobj.str);
// 2foo
var jsonstr = JSON.stringify(jsonobj);
// cannot do much with this
To send it to the server via an Ajax call, though, you need to serialize (stringify) it first. Likewise, you need to deserialize (parse) from a string into an object when receiving JSON back from the server.
Great question. The difference is transfer format.
JSON is only the 'Notation' of a JavaScript Object, it is not actually the JavaScript 'object-literal' itself. So as the data is received in JSON, it is just a string to be interpreted, evaluated, parsed, in order to become an actual JavaScript 'Object-Literal.
There is one physical difference between the two, and that is quotation marks. It makes sense, that JSON needs to be a string to be transferred. Here is how:
//A JavaScript Object-Literal
var anObj = { member: 'value'}
//A JSON representation of that object
var aJSON = { "member":"value" }
Hope that helps. All the best! Nash
I think a parsed json string should be the string data into the actual javascript objects and data arrays (or whichever language the json string contains)
The JSON object contains methods for parsing JSON and converting values to JSON.
It can't be called or constructed, and aside from its two method properties it has no interesting functionality of its own.
JSONParser parser = new JSONParser();
Object object = parser.parse(Message.toString());
JSONObject arObj = (JSONObject) object;