How to convert Array[Byte] to JSONObject in Scala - gson

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)
}

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 from Java to Xamarin C#

Can someone help me convert the following from Java to C# (Xamarin)?
I tried a couple of different ways, but I cannot get it to work.
The code is:
HttpPost post = new HttpPost(url);
// Break out all extra HTTP header lines and add it to the HttpPost object
for (String line : contentType.replace("\r", "\n").split("\n")) {
if (line.length() > 0 && line.contains(":")) {
String[] parts = line.split(":", 2);
if (parts.length == 2) {
post.addHeader(parts[0].trim(), parts[1].trim());
}
}
}
// Create a byte array entity for the POST data, the content
// type here is only used for the postEntity object
ByteArrayEntity postEntity = new ByteArrayEntity(challenge);
postEntity.setContentType("application/octet-stream");
post.setEntity(postEntity);
// Create a HttpClient and execute the HttpPost filled out above
HttpClient client = new DefaultHttpClient();
HttpResponse httpResponse = client.execute(post);
// Get the response entity out of the response
HttpEntity entity = httpResponse.getEntity();
If you are stuck with
post.SetEntity(postEntity);
then it converts to:
ByteArrayEntity postEntity = new ByteArrayEntity(challenge);
postEntity.SetContentType("application/octet-stream");
post.Entity = postEntity;
When converting to Java from C# you mostly have to change the property names to start with upperCase and then if you get stuck on certain objects I would look check out the Xamarin API Docs, HttpPost class linked here.

From Json String to XContentBuilder

I have a file in json format, is there a way to convert it to a XContentBuilder?
What I want to do is to read a file with some mapping and then convert it to XContentBuilder
Something like:
XContentBuilder builder = JsonXContent.contentBuilder().source(String json);
Usually the API should accept a String or byte[] so you shouldn't need to convert. Maybe you want CreateIndexRequestBuilder#addMapping(String, String)?
If you really, really, really want an XContentBuilder you can make an XContentParser and copy the contents to a builder. As of Elasticsearch 5.2 this should do it:
String message = "{\"test\":\"test\"}";
XContentBuilder b = XContentFactory.jsonBuilder().prettyPrint();
try (XContentParser p = XContentFactory.xContent(XContentType.JSON).createParser(NamedXContentRegistry.EMPTY, message)) {
b.copyCurrentStructure(p);
}
System.err.println(b.string());
You could probably also do something with raw but I don't think that is worth it.
Pre 5.2 you don't need the NamedXContentRegistry.EMPTY, part.
This seems to work for me:
import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.common.xcontent.XContentParser;
import org.elasticsearch.common.xcontent.XContentType;
...
String message = "{\"bob\": \"test\"}";
XContentParser parser = XContentFactory.xContent(XContentType.JSON).createParser(message.getBytes();
parser.close();
XContentBuilder builder = jsonBuilder().copyCurrentStructure(parser);
val x: XContentBuilder = XContentFactory.jsonBuilder().value("{\"bla\":\"blub\"}")
Not sure if this answers your question because you don't provide much information but you can also use strings to add a mapping to an IndexRequestBuilder:
new CreateIndexRequestBuilder(adminclient)
.addMapping("typeName", "{\"mapping\" : \"mapping\"}")
If you really want and need to create a XContentBuilder Object from a string you can do so like this:
String mapping = "{\"bla\":\"blub\"}"
XContentBuilder x = XContentFactory.jsonBuilder().value(mapping)

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.

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

*{
"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();

Resources