How to collect JSONArray using streams in JAVA - json

I wanted to collect in JSON Array so How I can able to do it?
Stream jsonArray = ((Set<?>) value).stream().map(e -> getJsonArray(e.toString())).collect(Collectors.toCollection(new JSONArray::put));
But here I am getting an error so How we can do it

Related

JSON API Document de-serializing and serializing using Spine Swift Library

I'm using Spine A Swift library for working with JSON:API
I want to understand how to serialize the data to take full advantage of the JSON API's
I'm using Serializer to achieve this as:
let serializer = Serializer()
serializer.registerResource(MyModel.self)
What i have got ?
let document = try! serializer.deserializeData(data) //data is my response as NSData
I'm able to get the JSON API Document with all the included relationships and data as
document.included
For this I'm casting MyModel to the required data as
MyModel = document.included[0] as! MyModel
As this is not the intended way to fully utilize the JSON :API, any suggestions and what am i missing ?

Save JSON Response as Variable to Deserialise with SwiftyJSON

I'm going to use either SwiftyJSON or EasyFastMapping to deserialise JSON data into variables and constants but I'm not sure on how to save the whole JSON file into its own object, if it is even possible.
I will be using Alamofire to handle the GET request and pull the JSON data down, is it possible to do it like this?
How I want it to work:
1. Alamofire pulls down the JSON data
Alamofire puts the data into an object
SwiftyJSON accesses the downloaded data and allows me to put individual parts of the data into separate variables and constants.
You could take a look at the documentation for SwiftyJSON and Alamofire and you will find plenty of examples.
From Alamofire Readme:
Alamofire.request("https://httpbin.org/get").responseJSON { response in
debugPrint(response)
if let json = response.result.value {
print("JSON: \(json)")
}}
From SwiftJSON Readme:
let json = JSON(data: dataFromNetworking)
if let userName = json[0]["user"]["name"].string {
//Your implementation here
}
You can also create a separate response object and deserialize all the response JSON into the object. Also take a look at the built-in JSONSerialization API in the Foundation framework.

Parsing JSON Data from URL with Android Studio

I'm trying to parse JSON data from URL and show the data in my app.
JSON Example (After accessing specific URL):
[{"placeID":"1","placeName":"Test Place","city":"New York","type":"Rest"..
How I can read this data and show a list of the places recieved from the API?
I've been trying ALL of the guides over the internet for parsing JSON data from URL with Android Studio and without. As a total beginner with Android developement, I couldn't make one working exmaple with json even when the author shared the final example for download. I hope you can help me in noob-friendly way and step by step or refer me to the right places.
Thank you!
I believe Android uses org.json as the JSON library, in which case something like this works to retrieve information about each place (assuming data is a valid JSON string)
try {
String data = "\"[{\"placeID\":\"1\",\"placeName\":\"Test Place\",\"city\":\"New York\",\"type\":\"Rest\"..";
JSONArray places = new JSONArray(data);
for (int i = 0; i < places.length(); i++)
JSONObject place = (JSONObject) places.get(i);
int id = place.getInt("id");
String name = place.getString("placeName");
String city = place.getString("city");
// etc...
// Do what you wish with the id, name, city and other variables.
// It loops through here for each item in the JSON variable.
}
} catch (JSONException e) {
e.printStackTrace();
}
This goes through each place in the JSON array and grabs some of the variables from it. It would probably be smart to create a data class and call it something like Place. You could then pass in the data with a constructor: new Place(id, name, city); (see this constructor for example: https://stackoverflow.com/a/22419370/5236779).

Json Parsing in Mirth OR Json in Mirth OR HL7 to JSON in Mirth

I want to use JSON as input of mirth channel and output like details Save in db or Create HL7 message.
In short Input as JSON Parse it and output as any format.
var object = {};
//Create JSON Object from HL7 Message.
object.mrn = msg['PID']['PID.3']['PID.3.1'].toString();
object.firstName = msg['PID']['PID.5']['PID.5.2'].toString();
object.lastName = msg['PID']['PID.5']['PID.5.1'].toString();
object.dob = msg['PID']['PID.7']['PID.7.1'].toString();
object.ssn = msg['PID']['PID.19']['PID.19.1'].toString();
//Create string from JSON Object.
var objjson = JSON.stringify(object);
logger.info(objjson);
//Create Json Object From JSON string.
var tt = JSON.parse(objjson);
Output
{"mrn":"1001","firstName":"COLLEEN","lastName":"OHALLAHAN","dob":"19850704","ssn":"123456789"}
HL7Message Sample
MSH|^~\&|ADT1|SHM|SHMADT|SHM|200812091126|SECURITY|ADT^A01^ADT_A01|MSG00001|P|2.5|
EVN|A01|200812091126||
PID|1|1001|1001^5^M11^ADT1^MR^SHM||OHALLAHAN^COLLEEN^^||19850704|F||2106-3|1200 N ELM STREET^^NEWPORT BEACH^CA^92660-1020^US^H|OC|(949) 555-1234|(949) 555-5678||S||PATID1001^2^M10^ADT1^AN^A|123456789|U1234567^CA|
NK1|1|OHALLAHAN^BRITTANY^M|SIS^SISTER||||N^NEXT-OF-KIN
PV1|1|I|2000^2012^01||||001122^ZOIDBERG^JOHN^|||SUR||||1|A0|
I was parsing through this page, and found your code Rikin patel. Actually when You create object and display it, it may appear in the console as a JSON data, when when you look your output it will be the normal XML driven format. But instead of the object when you use msg as below:
msg = JSON.stringify(object); //converting msg into JSON object
logger.info("json data:" + msg); //displaying the JSOn message
You will find the data being modified in the output.
As Per #Debugger, If some one want json file as input/Source then try this solution.
Mirth channel
Inbound Datatype as delimited text
Outbound DataType as Javascript
Make JavaScript Type of Destination and Write below code in Transformer:
//Create Json Object From JSON string.
var objJson = JSON.parse(messageObject.getRawData());
logger.info(objJson.propertyName);
Input:
{"mrn":"1001","firstName":"COLLEEN","lastName":"OHALLAHAN","dob":"19850704","ssn":"123456789"}
Output:
logger.info(objJson.firstName);
COLLEEN
Note:
Use connectorMessage.getRawData() instead of messageObject.getRawData() for Mirth 3.0+ version.
To receive JSON as Input in mirth channel, set inbound datatype as delimited text and in channel pre processor create Json object from received message and return the json object.
use the json object to get the details and store in some variables and use DB writer to save in db.
To build hl7 message, mirth provides few functions such as createSegment(seg name, index) to easily build your own hl7 message.

ServiceStack/Redis with Json over Http returns string not Json

I am trying to get CouchDB-like response from Redis - by using ServiceStack WebServices to access data stored via ServiceStack .Net RedisTypedClient onto Redis.
Now the web services are described as providing a CouchDB layer onto Redis. However, unlike equivalent CouchDB calls to a CouchDB, I never get back json but only strings - to be clear I do get back json but with the payload is in string format.
This applies to getting items from Redis List, Set and HashSet collections. All the items via either the xml,json or csv web services always deliver the payload as a string. Now I can see the serialized form of the type I stored in the string - such as a json array of strings or whatever, but the data is not delivered as json (or csv or xml) but as a string. I cannot find a query flag (.e.g. 'format=json' say) in any of the autogenerated documentation for these web services -which does say it delivers the payload as a string which is what I see.
Further apart from using the default jsv serializer through RedisTypedCLient I also tried directly calling the ServiceStack json serializer to serialize as json not jsv and also the Newtonsoft json serializer. None of this makes any difference. I did not expect it too as I imagine the default services would likely only manage the expected jsv version and would deliver anything else as strings. However I did not expect this of the internal serialization format.
So is it possible to get CouchDB like json responses from ServiceStack/Redis/Builtin-WebServices?
Update
Here is a typical query via the ServiceStack json web service:
http://myserver.com/redis/json/syncreply/GetAllItemsFromList?id=test
This is a Redis List collection containing strongly typed items:
type TestItem( gr,eType,pillar,offset) =
let mutable _gr = gr
let mutable _eType = eType
let mutable _pillar = pillar
let mutable _offset = offset
member x.Gr with get()= _gr and set(v) = _gr <- v
member x.EType with get()= _eType and set(v) = _eType <- v
member x.Pillar with get()= _pillar and set(v) = _pillar <- v
member x.Offset with get()= _offset and set(v) = _offset <- v
override x.ToString() = sprintf "%s %s %s %M" x.Gr x.EType x.Pillar x.Offset
The list collection was added using IRedisTypedClient Interface/API and I am expecting back a json list of json objects - a set of key/value pairs each pair corresponding to one of the four public properties in the type above. Instead I get
{"Items":[" {\"Gr\":\"BON13\",\"EType\":\"MARKET\",\"Pillar\":\"BON3.R0\",\"Offset\":0.0}","{\"Gr\":\"BOQ13\",\"EType\":\"MARKET\",\"Pillar\":\"BOQ3.R0\",\"Offset\":0.0}","{\"Gr\":\"BOU13\",\"EType\":\"MARKET\",\"Pillar\":\"BOU3.R0\",\"Offset\":0.0}","{\"Gr\":\"BOV13\",\"EType\":\"SETTLEPILLAR\",\"Pillar\":\"BOU3.R0\",\"Offset\":0.0}","{\"Gr\":\"BOZ16\",\"EType\":\"SETTLEPILLAR\",\"Pillar\":\"BOU3.R0\",\"Offset\":0.0}"],"ResponseStatus":{}}
In other words a string representation of the json object not the json object itself.
So again, how can I get back, in this case, a json list of of json objects rather than a json list of strings. (And the same goes for Sets, Dictionaries and more basic keyed json documents a la other NoSql dbs)?
I have the same issues getting back csv - it comes back as a string rather than either a csv of key/value pairs or a csv of keys and values and in XML where this,again, comes back as a string not not an XML format of key/value pairs.
Update 1
It does not need to be a strongly typed as above. It could be a list of a list of strings. In which case I get back a json list of strings rather than a json list containing items comprising json list of string.
Update 2
Whilst the problem clearly seems to be in the ServiceStack webservice implementation not being like CouchDB although it claims it is, here is some sample code to put the data into Redis via ServiceStack.
open System
open System.Collections.Generic
open ServiceStack.Redis
open System.Linq
type Repository() =
static let mutable __port = 6379
static let mutable __host = "myserver.com"
static let mutable __client = new RedisClient(__host,__port)
static member Client = __client :> IRedisClient
type Repository<'T>() =
let _client = Repository.Client
member x.GetList key =
use client = _client.As<'T>()
match _client.GetEntryType key with
| RedisKeyType.List ->
client.Lists.Item key |> client.GetAllItemsFromList
| _ -> new List<'T>()
member x.SetList (key, values: List<'T>) =
if (values.Count <> 0) then
use client = _client.As<'T>()
let list = client.Lists.Item key
values |> Seq.iter (fun x -> client.AddItemToList(list, x))
Usage
let repo = new Repository<List<string>>
let items = [["key0";"data0"];["key1";"data1"]]
|> Seq.map (fun kd -> List.init kd ))
|> List.init
repo.SetList("test",items)
The is just a cut and paste of longer code. I have tried this in c#, f# and with non default serialization as already stated. That is I have tried six different methods to date and none delivered the data payload as json objects via ServiceStack WebServices only as strings.
JSON data, when serialized and sent over the wire, is just a string. Your client needs to be JSON aware and de-serialize it into your object. The JsonClient for C# within ServiceStack is more than capable of handling this, and so are the many JavaScript frameworks that assist with AJAX calls (jQuery, AngularJS, etc).