Get JSON Data as String in Kotlin - json

I am using the following code which has no errors but I still get an expection error and not sure why:
fun getJsonDataFromAsset(context: Context, fileName: String): String? {
val jsonString: String
try {
jsonString = context.assets.open(fileName).bufferedReader().use { it.readText() }
} catch (ioException: IOException) {
ioException.printStackTrace()
return null
}
return jsonString
}

You can use Gson and AssetsManager for extracting json from asset-file. For example:
private fun createGson() = GsonBuilder().create()
fun getJsonStringFromAssets(fileName: String, context:Context): String {
val gson = createGson()
return gson.fromJson<Response>(getAssetsFileAsString(fileName, context), object : TypeToken<Response>() {}.type)
}
private fun getAssetsFileAsString(path: String, context:Context): String? {
return context.assets?.fileAsString(path)
}
private fun AssetManager.fileAsString(filename: String): String {
return open(filename).use {
it.readBytes().toString(Charset.defaultCharset())
}
}
Where 'Response' is your json data class.

Related

Setter not working when convert JSON to object class in typescript

In typescript, I want to convert JSON data to object class but every setter not running.
I have class CreateMeetingDto:
export class CreateMeetingDto {
private _meetingID : string;
private _name : string;
get meetingID(): string {
return this._meetingID;
}
set meetingID(value: string) {
this._meetingID = encodeURIComponent(value);
}
get name(): string {
return this._name;
}
set name(value: string) {
this._name = encodeURIComponent(value);
}
}
And this is code convert JSON to object class:
const jsonData = {
"meetingID": "1234",
"name": "Test Meeting"
};
const createMeetingDto = jsonData as CreateMeetingDto;
console.log(createMeetingDto.name);
// it is "Test Meeting" not "Test%20Meeting" => function in setter not working
How to run setter when convert json data to object class in typescript?

Spring API should return JSON instead of escaped String

I have Spring endpoint which is supposed to return JSON so it can be collapsed/expanded via Chrome. Is there a way to tell Spring that string in message is actual Json representation, and no need to escape double quotes
Endpoint declaration:
#GET
#Path("/validate/{id}")
#Produces("application/json")
Response validate(#Context HttpServletRequest request, #PathParam("id") String id);
Endpoint implementation:
public Response validate(HttpServletRequest request, String id) {
try {
return validatorService.validate(request, String id);
} catch(Exception e) {
throw new MyCustomException(e);
}
}
Exception Handler:
public class ExceptionHandler implements ExceptionMapper {
#Override
public Response toResponse(MyCustomException exception) {
String json = buildJsonResponse(exception);
Message message = new Message(json);
return Response.status(ERROR_HTTP_STATUS_CODE).entity(response).build();
}
}
public class Message {
String json;
public Message(String json) {
this.json = json;
}
public String getJson() {
return json;
}
}
Response:
"json": "{ \"key\": \"value\" }"
Expected response:
"json": { "key": "value" }
Solution:
private JsonNode convertToJson(String json) {
ObjectMapper mapper = new ObjectMapper();
try {
return mapper.readTree(json);
} catch (IOException e) {
return NullNode.getInstance();
}
}
Why don't you annotate your getter with #JsonRawValue
public class Message {
String json;
public Message(String json) {
this.json = json;
}
#JsonRawValue
public String getJson() {
return json;
}
}
That
You are converting your object to string in json format. Spring just returns a string value in json parameter. If you want to return json formated object not string do not convert your object to string( json ). Convert your json to Object type and delete the line below.
String json = buildJsonResponse(exception);
If you want to return custom json in string parameter convert your all object to json not only its variable.
You can just return string from your rest api with produces parameter like you added.
produces = "application/json"

Swift: JSONDecoder + Codable

I have three classes whom I want to parse from json which I receive from a server. the json structure is currenct.
those classes are:
public class HmoModel: Codable {
private var Id: Int
private var Name: String
}
public class SplashModel: Codable {
public var Hmos: [HmoModel]!
}
public class PatientSplashModel: SplashModel {
public var StressorsAnswers: [StressorsAnswerModel]!
}
I'm trying to parse a json this way:
do {
let patientSplash = try self.decoder.decode(PatientSplashModel.self, from: response.data)
} catch {
listener.onException(error)
}
but in patientSplash everything is nil.
I'm receiving the json using SwiftHTTP like this
HTTP.GET(ServerPatientApi.SPLASH, parameters: nil) { response in
if let error = response.error {
listener.onException(error)
return;
}
DispatchQueue.main.async (execute: {
do {
listener.onSplashLoaded(try self.decoder.decode(PatientSplashModel.self, from: response.data))
} catch {
listener.onException(error)
}
})
}
How to fix it? Hot to make a decoder parse json?
Thanks!
please add Codingkeys enum to your codable classes so codable could get objects by key for example
public class HmoModel: Codable {
private var Id: Int
private var Name: String
private enum CodingKeys: String, CodingKey {
case Id="id"
case Name="name"
}
}

Parse polymorphic child with Moshi

I ask here since I don't think this is a relevant question for Moshi GitHub issues.
I have card json variant #1:
{ "id":"some id",
"type":"GENERIC_MESSAGE",
"data": { "title":"Small error",
"message":"Please update some info",
"type":"ERROR"
}
}
and variant #2:
{ "id":"some id",
"type":"DATA_SCIENCE",
"data": { "cardData":
{ "message":"You spent...",
"title":"...last month"}
}
}
}
Here is my code for generic JSON adapter:
public class CardJsonAdapter
{
#Keep
static class CardJson
{
String id;
Card.Type type;
JSONObject data; <--- HERE is my problem
}
#FromJson
Card fromJson(#NonNull final CardJson json)
throws IOException
{
try
{
CardData data = getCardData(json);
return new Card(json.id, json.type, data);
}
catch (JSONException e)
{
throw new JsonDataException("Can not parse Card json");
}
}
private CardData getCardData(final #NonNull CardJson json)
throws JSONException
{
CardData data = null;
switch (json.type)
...
}
...
}
So by the card type, I already know how to parse data object. But I don't know how to get something generic in data. I can not set the type to String since Moshi crashes with BEGIN_OBJECT not expected error, I can not put Map<String, Object> it also fails with the error with the second json. And JsonObject is not crashing with parsing but is completely empty after parsing.
I can not find anything yet, so I'm asking your advice
I found the solution:
public class CardJsonAdapter
{
#Keep
static class CardDataJson
{
String title;
String message;
String type;
CardDataJson cardData;
}
#Keep
static class CardJson
{
String id;
Card.Type type;
CardDataJson data;
}
#FromJson
Card fromJson(#NonNull final CardJson json)
throws IOException
{
try
{
CardData data = getCardData(json);
return new Card(json.id, json.type, data);
}
catch (JSONException e)
{
throw new JsonDataException("Can not parse Card json");
}
}
private CardData getCardData(final #NonNull CardJson json)
throws JSONException
{
CardData data = null;
switch (json.type)
...
}
...
}
Moshi is just nulling fields that are not present in json

DeserializeObject Json

I have the following json data and i need to deserialize it. Btw i am using C# and i tried the following:
C#
// the data has been assigned to json variable
Result deserializedResult = JsonConvert.DeserializeObject<Result>(json);
Result class
private String _id = String.Empty;
private String[] _result = { };
private String _error = String.Empty;
public Result()
{
}
public String id
{
get { return _id; }
set { _id = value; }
}
public String[] result
{
get { return _result; }
set { _result = value; }
}
public String error
{
get { return _error; }
set { _error = value; }
}
JSon
{"id":1,"result":
[
{"id":12345,
"list_id":54321,
"is_test":false,
"type":"manual",
"creator_name":"Test Solutions"
},
{"id":54321,
"list_id":12345,
"is_test":false,
"type":"manual",
"creator_name":"Test Solutions"
}
],
"error":null}
ERROR
Additional information: Error reading string. Unexpected token: StartObject. Path 'result[0]', line 1, position 19.
I was missing something so obvious. Instead of another object e.g. Result class i was expecting an array. I fixed the issue editing Result property chaning
public String[] result { get; set; }
to
public List<Result> result { get; set; }
Thank you and sorry for bothering. Have a nice day