最近很多小伙伴都在问使用java创建json数据和java创建json这两个问题,那么本篇文章就来给大家详细解答一下,同时本文还将给你拓展ASP.NetMVC:如何基于原始Json数据创建JsonRe
最近很多小伙伴都在问使用java创建json数据和java 创建json这两个问题,那么本篇文章就来给大家详细解答一下,同时本文还将给你拓展ASP.Net MVC:如何基于原始Json数据创建JsonResult、java – 使用GSON创建JSON字符串、javascript – 使用JSON数据没有jQuery(sans getJSON)、javascript – 使用JSON数据的好的.NET库?等相关知识,下面开始了哦!
本文目录一览:- 使用java创建json数据(java 创建json)
- ASP.Net MVC:如何基于原始Json数据创建JsonResult
- java – 使用GSON创建JSON字符串
- javascript – 使用JSON数据没有jQuery(sans getJSON)
- javascript – 使用JSON数据的好的.NET库?
使用java创建json数据(java 创建json)
可以创建json字符串在网上进行传输,也可以将获取到的json字符串写入到文件
1.需要创建的json数据
2.项目结构
CreateJson.java
package testcreatejson;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
public class CreateJson {
public static void main(String[] args) {
//首先要创建一个整体的json对象
JsonObject object=new JsonObject();
//1.json字符串
//add:为当前json对象添加另一个json对象;addProperty:为当前json对象直接添加属性值
object.addProperty("cat", "it");
//2.json数组
JsonArray array=new JsonArray();
JsonObject language1=new JsonObject();
language1.addProperty("id", 1);
language1.addProperty("name", "java");
language1.addProperty("ide", "Eclipse");
array.add(language1);
JsonObject language2=new JsonObject();
language1.addProperty("id", 2);
language1.addProperty("name", "Swift");
language1.addProperty("ide", "Xcode");
array.add(language2);
JsonObject language3=new JsonObject();
language1.addProperty("id", 3);
language1.addProperty("name", "C#");
language1.addProperty("ide", "Visual Studio");
array.add(language3);
//将数组添加到Object中
object.add("languages", array);
//3.布尔类型的json数值
object.addProperty("pop", true);
System.out.println(object.toString());
}
}
3.运行结果截图
OK!!!
ASP.Net MVC:如何基于原始Json数据创建JsonResult
具有string
包含以下原始Json数据(为方便起见,已将其简化):
var MyString = "{ ''val'': ''apple'' }";
如何创建一个JsonResult
表示的对象MyString
?
我试图使用Json(object)方法。但是它将原始json数据作为字符串-逻辑上:P-处理。因此,返回的HTTP响应如下所示:
"{ ''val'': ''apple'' }"
而不是给定的原始Json数据:
{ ''val'': ''apple'' }
这是我想要实现的目标 :
答案1
小编典典上的Json()
方法Controller
实际上是创建新的辅助方法JsonResult
。如果我们查看此类*
的源代码,我们会发现它实际上并没有做太多的工作-
只需将内容类型设置为application/json
,使用来序列化数据对象JavaScriptSerializer
,然后将其写入结果字符串即可。行为(减去序列化,因为您已经完成了),ContentResult
而是从控制器返回a
。
public ActionResult JsonData(int id) { var jsonStringFromSomewhere = "{ ''val'': ''apple'' }"; // Content() creates a ContentResult just as Json() creates a JsonResult return Content(jsonStringFromSomewhere, "application/json");}
*从MVC2开始,JsonResult
如果用户正在发出HTTP GET请求(而不是POST),也会引发异常。允许用户使用HTTP GET检索JSON具有安全隐患,在您自己的应用程序中允许这样做之前,应注意安全隐患。
java – 使用GSON创建JSON字符串
public class Student { public int id; public String name; public int age; }
现在我想创建新的学生,
//while create new student Student stu = new Student(); stu.age = 25; stu.name = "Guna"; System.out.println(new Gson().toJson(stu));
这给我以下输出,
{"id":0,"name":"Guna","age":25} //Here I want string without id,So this is wrong
所以这里我想要String
{"name":"Guna","age":25}
如果我想编辑老学生
//While edit old student Student stu2 = new Student(); stu2.id = 1002; stu2.age = 25; stu2.name = "Guna"; System.out.println(new Gson().toJson(stu2));
现在的输出是
{"id":1002,"age":25} //Here I want the String with Id,So this is correct
如何使用一个字段[某些时候]创建JSON字符串,没有字段[在某个时间点].
任何帮助将是非常可观的.
谢谢.
解决方法
public class Student { public int id; @Expose public String name; @Expose public int age; }
并使用以下方法从对象中获取Json字符串
private String getJsonString(Student student) { // Before converting to GSON check value of id Gson gson = null; if (student.id == 0) { gson = new GsonBuilder() .excludeFieldsWithoutExposeAnnotation() .create(); } else { gson = new Gson(); } return gson.toJson(student); }
如果设置为0,它将忽略id列,否则将返回带有字段的json字符串.
javascript – 使用JSON数据没有jQuery(sans getJSON)
解决方法
// If we're requesting a remote document // and trying to load JSON or Script with a GET if ( s.dataType === "script" && type === "GET" && remote ) { var head = document.getElementsByTagName("head")[0] || document.documentElement; var script = document.createElement("script"); script.src = s.url; if ( s.scriptCharset ) { script.charset = s.scriptCharset; } // Handle Script loading if ( !jsonp ) { var done = false; // Attach handlers for all browsers script.onload = script.onreadystatechange = function() { if ( !done && (!this.readyState || this.readyState === "loaded" || this.readyState === "complete") ) { done = true; success(); complete(); // Handle memory leak in IE script.onload = script.onreadystatechange = null; if ( head && script.parentNode ) { head.removeChild( script ); } } }; } // Use insertBefore instead of appendChild to circumvent an IE6 bug. // This arises when a base node is used (#2709 and #4378). head.insertBefore( script,head.firstChild ); // We handle everything using the script element injection return undefined; }
使用一个JSON Parser.你也可以使用eval,但它是一个赞成JSON解析器的皱眉头.
这是jQuery的内部parseJSON方法:
parseJSON: function( data ) { if ( typeof data !== "string" || !data ) { return null; } // Make sure leading/trailing whitespace is removed (IE can't handle it) data = jQuery.trim( data ); // Make sure the incoming data is actual JSON // Logic borrowed from http://json.org/json2.js if ( /^[\],:{}\s]*$/.test(data.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g,"@") .replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,"]") .replace(/(?:^|:|,)(?:\s*\[)+/g,"")) ) { // Try to use the native JSON parser first return window.JSON && window.JSON.parse ? window.JSON.parse( data ) : (new Function("return " + data))(); } else { jQuery.error( "Invalid JSON: " + data ); } },
javascript – 使用JSON数据的好的.NET库?
任何其他好的JSON库的.NET?
解决方法
例:
public class Person { public string Name { get;set;} public int Age { get;set; } public Person() { } } public class MyService : JsonRpcHandler { [JsonRpcmethod("getBob")] public Person GetBob() { return new Person() { Name="Bob",Age=20}; } }
和Javascript:
var service = new MyService(); var result = service.getBob(); alert(result.name); // JSON objects are camel-cased.
今天的关于使用java创建json数据和java 创建json的分享已经结束,谢谢您的关注,如果想了解更多关于ASP.Net MVC:如何基于原始Json数据创建JsonResult、java – 使用GSON创建JSON字符串、javascript – 使用JSON数据没有jQuery(sans getJSON)、javascript – 使用JSON数据的好的.NET库?的相关知识,请在本站进行查询。
本文标签: