The client side expects JSON string in the below format
descriptions": [
{
"lang": "string",
"size": "string",
"text": "string",
"type": "string"
}
],
, but the received JSON is a bit different - like below
"descriptions":{
"desc":[
{
"size":string,
"lang":"string",
"type":"string",
"content":"string"
}
]
},
Is there anyway to ignore the "desc" part - for eg. using a JSON annotation ? Context: I am passing this JSON through a REST API call and it will be automatically converted to a Java object at the receiving end.
A simple
descriptions = descriptions.desc;
will do.
You just construct the object you need:
var clientDescriptions = descriptions.desc.map(function(d) {
size: d.size,
type: d.type,
lang: d.lang,
content: d.text
});
If you are using Gson, it is possible to use custom JsonDeserializer / JsonSerializer for your Java model. Your model object and API can then be cleanly implemented without having to deal with the different json structures.
In my personal experience, the backend has a bug and must be solved, it mustn't be sending malformed data.In the long run it is the best solution.
Related
I've got json file with some nested objects inside subs in it:
{
"version": 1,
"data": [{
"married": true,
"subs":[
{
"name":{
"sub1":{}
**},**
},
]
},
]}
If I add another 'name' object (with comma as separator), jsonDecode returns nothing.
if there goes single object, without comma - it's ok.
My Json structure is correct, and it's not restricted to use nested objects at all. Please anyone help.
This line has problem **},** and if changed to }, the problem will be solved..
you can check your json by online tools (e.g https://jsonformatter.curiousconcept.com/#)
I have a problem of huge http response with a json slab, where only portion is point of interest.
I cannot change the response structure.
here is an example
{
"searchString": "search",
"redirectUrl": "",
"0": {
"numRecords": 123,
"refinementViewModelCollector": {},
// Lots of data here
"results": [
{
"productCode": "123",
"productShortDescription": "Desc",
"brand": "Brand",
"productReview": {
"reviewScore": 0
},
"priceView": {
"salePriceDisplayable": false,
},
"productImageUrl": "url",
"alternateImageUrls": [
"url1"
],
"largeProductImageUrl": "url4",
"videoUrl": ""
},
{
"productCode": "124",
"productShortDescription": "Desc",
"brand": "Brand",
"productReview": {
"reviewScore": 0
},
"priceView": {
"salePriceDisplayable": false,
},
"preOrder": false,
"productImageUrl": "url",
"alternateImageUrls": [
"url1"
],
"largeProductImageUrl": "url4",
"videoUrl": ""
}
]
//lots of data here
}
}
My point of interest is entries in results Jason Array, but the are sitting in the middle of json
I created a small Play WS Client like this:
val wsClient: WSClient = ???
val ret = wsClient.url("url").stream()
ret.flatMap { response =>
response.body.via(JsonFraming.objectScanner(1024))
.map(_.utf8String)
.runWith(Sink.foreach(println))
}
this will not work because it will take whole json slab as Json object. I need to skip some data until "results": entry appear in the stream, then start parsing entries and skip all the rest.
Any ideas how to do this?
Check out Alpakka's JSON module, which can stream specific parts of a nested JSON structure:
response
.body
.via(JsonReader.select("$.0.results[*]"))
.map(_.utf8String)
.runWith(Sink.foreach(println)) // or runForeach(println)
There are parsers that support parsing as a stream. For a good example check out this Circe example https://github.com/circe/circe/tree/master/examples/sf-city-lots
I'd love a better, Scala-specific answer to this question, but check out the "Mixed Reads Example" in the documentation for Google's GSON library:
https://sites.google.com/site/gson/streaming
Gson also supports mixed streaming & object model access. This lets your application have the best of both worlds: the productivity of object model access with the efficiency of streaming
...
This code reads a JSON document containing an array of messages. It steps through array elements as a stream to avoid loading the complete document into memory. It is concise because it uses Gson’s object-model to parse the individual messages
This should have great memory-performance (the code reads from a Java InputStream, so the full structure is never in memory), but may require some effort to get your results into Scala case classes.
I have this JSON that is returned from a REST-service I'm using.
{
"id": "6804",
"signatories": [
{
"id": "12125",
"fields": [
{
"type": "standard",
"name": "fstname",
"value": "John"
},
{
"type": "standard",
"name": "sndname",
"value": "Doe"
},
{
"type": "standard",
"name": "email",
"value": "john.doe#somwhere.com"
},
{
"type": "standard",
"name": "sigco",
"value": "Company"
}
]
}
]
}
Currently I'm looking into a way to parse this with json4s, iterating over the "fields" array, to be able to change the property "value" of the different objects in there. So far I've tried a few json libs and ended up with json4s.
Json4s allows me to parse the json into a JObject, which I can try extract the "fields" array
from.
import org.json4s._
import org.json4s.native.JsonMethods._
// parse to JObject
val data = parse(json)
// extract the fields into a map
val fields = data \ "signatories" \ "fields"
// parse back to JSON
println(compact(render(fields)))
I've managed to extract a Map like this, and rendered it back to JSON again. What I can't figure out though is, how to loop through these fields and change the property "value" in them?
I've read the json4s documentation but I'm very new to both Scala and it's syntax so I'm having a difficult time.
The question becomes, how do I iterate over a parsed JSON result, to change the property "value"?
Here's the flow I want to achieve.
Parse JSON into iterable object
Loop through and look for certain "names" and change their value, for example fstname, from John to some other name.
Parse it back to JSON, so I can send the new JSON with the updated values back.
I don't know if this is the best way to do this at all, I'd really appreciate input, maybe there's an easier way to do this.
Thanks in advance,
Best regards,
Stefan Konno
You can convert the json into an array of case class which is the easiest thing to do. For example: you can have case class for Fields like
case class Field(`type`: String, name: String, value: String)
and you can convert your json into array of fields like read[Array[Field]](json) where json is
[
{
"type": "standard",
"name": "fstname",
"value": "John"
},
...
]
which will give you an array of fields. Similarly, you can model for your entire Json.
As now you have an array of case classes, its pretty simple to iterate the objects and change the value using case classes copy method.
After that, to convert the array of objects into Json, you can simply use write(objects) (read and write functions of Json4s are available in org.json4s.native.Serialization package.
Update
To do it without converting it into case class, you can use transformField function
parse(json).transformField{case JField(x, v) if x == "value" && v == JString("Company")=> JField("value1",JString("Company1"))}
I am using Neo4j and ExtJS in my application.
One good thing is that both handle JSON with array structure.
Neo4j returns and ExtJS can consume JSON like this:
{
columns: ["name", "age"],
data: [
["Peter", 34],
["Mike", 52]
]
}
instead of:
[
{"name": "Peter", "age" 34},
{"name": "Mike", "age" 52},
]
However, from my application server's HTTP API I want people to be able to choose which one of these JSON structures to receive.
So they are both JSON which means the HTTP header should be "Accept": "application/json". But how should I allow them to pick either one of the structures? Should they set a header or a query param? What is best practice?
I think that a simple param in the request would be enough.
I have node.js REST api, which returns following object
[
{
"word": "word"
},
{
"word": "ability"
},
{
"word": "about"
}
]
Can someone please let me how to parse this object in ActionScript3 SDK4.6
Thanks in Advance!!!
JSON parsing is included in the default package.
var json:Object = JSON.parse("[{\"word\": \"word\"},{\"word\": \"ability\"},{\"word\": \"about\"}]");
Default JSON parsing is much higher performance than as3corelib implementation.