How to parse a simple array with Gson that contains mixed types? - gson

*{
"data":["v",
{
"value1":6,
"value2":0,
"value3":1
}
]
}*
How to parse a simple array with Gson that contains mixed types?

The easiest way is to parse into a JsonElement:
JsonElement parsed = new JsonParser().parse(json);
You can use JsonElement's APIs to interrogate the parsed object as necessary.

Gson gson = new Gson();
JsonElement element = gson.fromJson(jsonInputStr, JsonElement.class);
JsonArray array = element.getAsJsonArray();

Related

Fetch the JSONobject value to a variable which is inside the dynamically generated JSONobject

We have below JSON response which has dynamically getting one of the JSONobject which has other objects inside. Tried some of the solutions provided here, but unable to get the values, every time getting 'null'.
{
"Result": {
"12987654": {//this value 1298.. is dynamically getting generated at every response.
"Tests1": {
"test1": -0.85,
"test2": 0.016,
"tests3": "FAIL"
},
"Tests2": {
"test21": "PASS",
"test22": "PASS",
"test23": "FAIL"
}
}
}
}
Now Trying to get value of inside this dynamically (1298..) generating object, like Tests2.teset21.
If tried as
JSONPath js.get("Results.1298.Tests1.test1")//able to get the value. however here 1298 is hardcoded and this value changes in the next run.
If tried as below, getting value as null.
import com.google.gson.JsonObject;
JsonObject jsonObjectResponse = (JsonObject) new JsonParser().parse(responseInString);
JsonObject Result = jsonObjectResponse.get("loanResult").getAsJsonObject();
SysOut(Result)//gives null
OR, trying below also gives null
JsonElement jelement = new JsonParser().parse(responseInString);
JsonObject ResultObj = jelement.getAsJsonObject();
System.out.println("ResultObj value is: " + loanResultObj.get("tests21"));
Please guide how to get value inside of dynamically generating Jsonobject.
Finally after many attempts, could understand using Gson to get the value. For my issue, the id which dynamic goes from Request. With below code could solve issue:
Gson gsonResp = new Gson();
String responseInString = response.asString();
JsonObject jsonObjectNewResponse = gsonResp.fromJson(responseInString, JsonObject.class);
String test12 = jsonObjectNewResponse.getAsJsonObject("Result").getAsJsonObject(<dynamicID which is been extracted from Req in the form of String>). getAsJsonObject("test1").get("test12").getAsString();

How to convert Array[Byte] to JSONObject in Scala

I have an Array[Byte]. I am trying to convert it into JSON Object.
I tried using GSON library. I got the String representation of the JSON Object. I am stuck at this point and also not sure if this is the correct way.
def getJSONObject(array : Array[Byte]) : JSONObject = {
val jsonString = new Gson().toJson(array)
}

Evaluate expressions as well as regex in single field in custom processors of Nifi

In my custom processor I have added below field
public static final PropertyDescriptor CACHE_VALUE = new PropertyDescriptor.Builder()
.name("Cache Value")
.description("Cache Value")
.required(true)
.addValidator(StandardValidators.NON_EMPTY_VALIDATOR)
.expressionLanguageSupported(ExpressionLanguageScope.FLOWFILE_ATTRIBUTES)
.build();
Where I expect to read flowfile attributes like ${fieldName}
as well as regex like .* to read full content or some part of content like $.nodename.subnodename
For that I have added below code
for (FlowFile flowFile : flowFiles) {
final String cacheKey = context.getProperty(CACHE_KEY).evaluateAttributeExpressions(flowFile).getValue();
String cacheValue = null;
cacheValue = context.getProperty(CACHE_VALUE).evaluateAttributeExpressions(flowFile).getValue();
if (".*".equalsIgnoreCase(cacheValue.trim())) {
final ByteArrayOutputStream bytes = new ByteArrayOutputStream();
session.exportTo(flowFile, bytes);
cacheValue = bytes.toString();
}
cache.put(cacheKey, cacheValue);
session.transfer(flowFile, REL_SUCCESS);
}
How to achieve this one some part of content like $.nodename.subnodename.
Do I need to parse the json or is there any other way?
You will either have to parse the JSON yourself, or use an EvaluateJsonPath processor before reaching this processor to extract content values out to attributes via JSON Path expressions, and then in your custom code, reference the value of the attribute.

Json.Net for serializing an object graph

I was using the .Net built in JavaScriptSerializer() to Serialize a JSON string coming from a webpage.
I heard that Newtonsoft.Json.Net have a better serializer, so I thought I would give it a try.
I load my json string, here is a sample.
jsonString = "{\"jName\":\"MB-CEF3-4\",\"StartDate\":\"08/20/2013 00:00\",\"EndDate\":\"08/29/2013 00:00\",\"JType\":\"General\",\"SetupParams\":[
{\"Name\":\"PTitle\",\"Title\":\"01. Period Title\",\"Type\":\"text\",\"Value\":\"TestName\"},
{\"Name\":\"PStart\",\"Title\":\"02. Period Start\",\"Type\":\"datetime\",\"Value\":\"08/20/2013\"},
{\"Name\":\"Target\",\"Title\":\"03. Target\",\"Type\":\"int\",\"Value\":\"1\"},
{\"Name\":\"URL\",\"Title\":\"04. Completion Report URL\",\"Type\":\"url\",\"Value\":\"http://www.example.com\"},
{\"Name\":\"FormTitle\",\"Title\":\"05. Form Title\",\"Type\":\"text\",\"Value\":\"ct\"},
{\"Name\":\"nvTypes\",\"Title\":\"{B6E71787-EB51-45CF-B408-552F79AF2E7B}\",\"Type\":\"nvc\",\"Value\":\"Use of nv tools\"}, {\"Name\":\"NVCoachingTypes\",\"Title\":\"\",\"Type\":\"nvc\",\"Value\":\"\"}]}";
JavaScriptSerializer scs = new JavaScriptSerializer();
Dictionary<String, Object> aps = (Dictionary<String, Object>)scs.DeserializeObject(ActSetupConfigs);
I then would pass this Dictionary into another worker class, where it is deserialized..
I was using: var parameters = ((object[])Parameters["SetupParams"]);
and it would load the an array of objects.
I tried to do the same with Json.Net
Dictionary<String, Object> aps = JsonConvert.DeserializeObject<Dictionary<String, Object>>(ActSetupConfigs);
but when I try to deserialize it I don't get an array of objects, instead the sub collection of the array is just a string....so it throws an exception. How can I use Json.net to serialize all the sub-collections?
The sub-collection of the SetupParams array is not a string, it is a JToken, which is a generic container object that JSON.Net uses to hold a JSON structure. Fortunately, it is easy to extract values from a JToken. Try using this code instead.
JToken aps = JToken.Parse(jsonString);
foreach (JToken param in aps["SetupParams"])
{
Console.WriteLine("Name: " + param["Name"].Value<string>());
Console.WriteLine("Title: " + param["Title"].Value<string>());
Console.WriteLine("Type: " + param["Type"].Value<string>());
Console.WriteLine("Value: " + param["Value"].Value<string>());
Console.WriteLine();
}
You can parse the above json response using json.net like,
dynamic initialresp=JValue.Parse(jsonString);
string jname=Convert.ToString(initialresp.jname);
...
...
dynamic setupparams=JArray.Parse(Convert.ToString(initialresp.SetupParams));
foreach(var item in setupparams)
{
string name=Convert.Tostring(item.Name);
string title=Convert.Tostring(item.Title);
...
...
}
Hope this helps.

GSON - Deserialize java generics collection

I am trying to deserialize an arraylist from the DB withiout a success.
this is the way I put my objects:
for (int i = 0; i < dealsList.size(); i++) {
ServerServicesInternalWrapper.reportDeal(Json.toWrap(dealsList.get(i)));
}
where
public static <T> String toWrap(T t) {
JsonWrapperWithType wrapper =
new JsonWrapperWithType(t.getClass(),gson.toJson(t));
return to(wrapper);
}
this is the way I select
return (List<DealBean>)session.createCriteria(DealBean.class).add(Restrictions.eq("portfolio", portfolio)).list();
and then I Gson it to a string using
JsonWrapperWithType wrapper =
new JsonWrapperWithType(t.getClass(), gson.toJson(t));
return gson.toJson(wrapper );
and this is the way I de-gson the object
And now - the exception
Type listType = new TypeToken<List<DealBean>>(){}.getType();
List<DealBean> dealsForPortfolio =
(List<DealBean>)gson.fromJson(dealsForPortfolioString,type);
com.google.gson.JsonParseException: The JsonDeserializer
com.google.gson.DefaultTypeAdapters$CollectionTypeAdapter#1f899e9 failed to deserialized
json object {"type":"java.util.ArrayList","content":"[{\"ID\":5,\"tradable\":
...
Caused by: java.lang.IllegalStateException: This is not a JSON Array.
Gson expects a list of Json objects like: [{obj1}, {obj2}, ... , {objN}]
I'm not sure from code you posted here what your intentions were but it seems to me like you are wrapping a list with parent object.
In the case you want it like that, you need to make your own deserializer.

Resources